How to distinguish objects Future, FutureTask, and CompletableFuture by their purpose and features?
sobes.tech AI
Answer from AI
Future is an interface that represents the result of an asynchronous operation. It allows you to check if the task has completed, cancel it, and retrieve the result, blocking if it is not yet ready.
FutureTask is a concrete implementation of the Future interface and also implements Runnable. It can be used to run tasks in a separate thread and to obtain the result. FutureTask can be passed to an Executor or run manually.
CompletableFuture is an extended implementation of Future that appeared in Java 8. It supports functional programming and allows building chains of asynchronous operations using methods like thenApply, thenCompose, exceptionally, etc. It is a more powerful and flexible tool for working with asynchronous code.
Example of using CompletableFuture:
CompletableFuture.supplyAsync(() -> {
// Long operation
return "Result";
}).thenApply(result -> {
return result.toUpperCase();
}).thenAccept(finalResult -> {
System.out.println(finalResult);
});