![]() |
VOOZH | about |
CompletableFuture is used to perform asynchronous and non-blocking tasks efficiently. Introduced in Java 8, it allows tasks to run in separate threads and provides powerful methods to manage, combine, and process results of asynchronous computations.
CompletableFuture can be created using the supplyAsync() method, which runs a task asynchronously in a separate thread and returns the result later.
Output:
Hello from CompletableFutureExplanation: This creates a CompletableFuture that will execute the lambda function passed to supplyAsync in a separate thread. And after the execution, the result lambda function is returned by CompletableFuture Object.
It allows multiple asynchronous tasks to be combined and processed together using composition methods. These methods create a new CompletableFuture based on the result of previous tasks.
Output:
Hello WorldExplanation: This creates two instances of CompletableFuture that return "hello" and "world". And using thenCombine, the result of both the CompletableFutures are concatenated and returned as a final result.
CompletableFuture provides methods to manage multiple asynchronous tasks running in parallel. It helps coordinate tasks and process results after one or all tasks are completed.
allOf() waits for all CompletableFuture tasks to complete. anyOf() completes when any one of the tasks finishes first. Future1 Result: 10 Future2 Result: 20
Explanation: This program demonstrates how to execute multiple CompletableFuture tasks in parallel using allOf(). The join() method waits for all tasks to complete before fetching their results using get().
Note: The allOf() method is used to combine the results of multiple CompletableFuture instances.
CompletableFuture provides built-in methods to handle exceptions that occur during asynchronous execution. These methods help manage errors and continue program execution smoothly.
0
Explanation: This example demonstrates exception handling in CompletableFuture using exceptionally(). When an error occurs in the async task, it provides a fallback value so the program continues smoothly.