Junior — Middle
Can there be additional classes in Java that implement the Future interface, and what are they called?
sobes.tech AI
Answer from AI
Yes, in Java, besides the standard Future interface, there are additional classes and interfaces that implement or extend the functionality of Future.
The main ones are:
-
FutureTask — a class that implements the
RunnableFutureinterface, which extendsFutureandRunnable. It allows running asynchronous tasks and obtaining the result. -
CompletableFuture — extends
Futureand provides a more powerful API for asynchronous programming, including chaining calls, exception handling, and combining multiple tasks. -
RunnableFuture — an interface that combines
RunnableandFuture, used for tasks that can be run and have a result.
Example of using FutureTask:
Callable<Integer> callable = () -> {
Thread.sleep(1000);
return 123;
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
Integer result = futureTask.get(); // blocks until the result is available
System.out.println(result); // 123