Senior
What is the purpose of the Future interface? How does CompletableFuture differ?
sobes.tech AI
Answer from AI
The Future interface in Java represents the result of an asynchronous operation that can be obtained in the future. It allows checking whether the operation has completed, canceling it, or retrieving the result, blocking the current thread if the result is not yet available.
CompletableFuture is an extended implementation of Future that supports functional chaining programming and allows explicitly completing asynchronous operations, as well as combining multiple such operations.
Main differences:
Futuredoes not support methods for composition or processing the result without blocking.CompletableFutureprovides methods for asynchronous execution, chaining (thenApply,thenCompose), error handling (exceptionally), and can be manually completed.
Example of using CompletableFuture:
CompletableFuture.supplyAsync(() -> {
// Long operation
return "Result";
}).thenApply(result -> {
// Process result
return result.toUpperCase();
}).thenAccept(finalResult -> {
System.out.println(finalResult);
});
Thus, CompletableFuture is more flexible and powerful for working with asynchronous code compared to the basic Future.