Junior — Middle
What is the purpose and main functions of the CompletableFuture class in Java?
sobes.tech AI
Answer from AI
The CompletableFuture class in Java is designed for working with asynchronous computations and allows creating chains of tasks that execute in the future.
Main features and capabilities:
- Asynchronous task execution — launching operations in a separate thread without blocking the main thread.
- Combining multiple tasks — you can merge several
CompletableFutureinstances using methods likethenApply,thenCombine,thenAccept, and others. - Handling results and errors — allows specifying actions upon successful completion or in case of exceptions.
- Support for call chains — simplifies building complex asynchronous processes.
Example of usage:
CompletableFuture.supplyAsync(() -> {
// Long operation
return "Result";
}).thenApply(result -> {
// Processing the result
return result.toUpperCase();
}).thenAccept(finalResult -> {
System.out.println("Result: " + finalResult);
});
This code runs an asynchronous task, transforms the result, and outputs it without blocking the main thread.