What is CompletableFuture?
A CompltableFuture is used for asynchronous programming. Asynchronous programming means writing non-blocking code. It runs a task on a separate thread than the main application thread and notifies the main thread about its progress, completion or failure.
In this way, the main thread does not block or wait for the completion of the task. Other tasks execute in parallel. Parallelism improves the performance of the program.
A CompletableFuture is a class in Java. It belongs to java.util.cocurrent package. It implements CompletionStage and Future interface.
Hence, it is an element of a chain.
When more than one thread attempt to complete - complete exceptionally or cancel a CompletableFuture, only one of them succeeds.
Future vs. CompletableFuture
A CompletableFuture is an extension to Java's Future API which was introduced in Java 8.
A Future is used for asynchronous Programming. It provides two methods, isDone() and get(). The methods retrieve the result of the computation when it completes.
Limitations of the Future
Future has so many limitations, that's why we have CompletableFuture. CompletableFuture provides a broad set of methods for creating multiple Futures, chaining, and combining. It also has comprehensive exception handling support.
Creating a CompletableFuture
We can create a CompletableFuture only by using the following no-argument constructor.
The most frequently used CompletableFuture methods are:
Exception Handling of CompletableFuture
Consider the following figure, which represents the five CFs:
Suppose Five CFs in execution and CF21 raises an exception then all the depending CF (CF31 and CF41) are in error. It means that:
Consider the following figure, in which we have created CF30 with an exception.
When CF21 executes normally, then CF30 just transmits the value. If it raises an exception, CF30 handles it and generate value for CF31.
There are three method to handle an exception: