Middle
What are the purposes of the Future and CompletableFuture classes in Java?
sobes.tech AI
Answer from AI
The Future and CompletableFuture classes in Java are designed for working with the results of asynchronous computations.
-
Future represents a result that will be available in the future. It can be used to check if the computation is complete, get the result (the get method blocks if the result is not ready), or cancel the task.
-
CompletableFuture extends Future, providing a convenient API for composing asynchronous operations, handling results without blocking, chaining calls, and exception handling. It supports functional methods like thenApply, thenAccept, thenCompose, and others, which facilitate building complex asynchronous scenarios.
Example of using CompletableFuture:
CompletableFuture.supplyAsync(() -> {
// Long operation
return "Result";
}).thenApply(result -> {
// Process result
return result.toUpperCase();
}).thenAccept(finalResult -> {
System.out.println(finalResult);
});