Junior — Middle
Explain the differences between Future and CompletableFuture classes in the context of asynchronous programming in Java.
sobes.tech AI
Answer from AI
In Java, the interface Future represents the result of an asynchronous operation that can be obtained later. It allows you to check if the task is completed, cancel it, and get the result, blocking if necessary.
CompletableFuture is an extension of Future that appeared in Java 8, supporting more advanced features for asynchronous programming. The main difference:
- Future does not support chaining and composition of asynchronous tasks. To get the result, you need to call
get(), which blocks the thread. - CompletableFuture allows creating chains of tasks, processing results and errors without blocking, using methods like
thenApply(),thenCompose(),exceptionally(). - CompletableFuture supports programmatic completion (method
complete()), which is not possible with a regular Future.
Example of using CompletableFuture:
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);
Thus, CompletableFuture is a more powerful and flexible tool for asynchronous programming compared to Future.