Introduced in Java 8 (2014).
A java.util.concurrent.CompletableFuture
is a complete implementation of both Future
and CompletionStage
.
CompletableFuture provides static methods as means to execute the tasks.
CompletableFuture allows for chaining and combining outcomes from multiple other CompletableFutures.
Pattern in method name | Description |
---|---|
|
Perform a task without a return value, using a Runnable. |
|
Perform a task that returns a value, using a Supplier. |
Synchronicity is either Sync or Async
Pattern in method name | Description |
---|---|
<nothing> |
synchronous, performed by the thread running the CompletableFuture. |
|
asynchronous, performed by default by the ForkJoinPool.commonPool unless an executor is provided. |
There are two methods to retrieve the results.
Both wait for the CompletableFuture to complete, then return the result if successful.
Unsuccessful outcomes are due to cancellation, exceptional outcomes and interruptions.
Method name | Description |
---|---|
|
Return the result. Throws checked exceptions when unsuccessful. |
|
Return the result. Throws unchecked runtime exceptions when unsuccessful. |
Pattern in method name | Description |
---|---|
Chaining |
|
|
Chain two CompletableFuture, the second executed after the first using the result of the first as a value in a Function, returning a CompletableFuture. |
|
Chain two CompletableFuture, when both are completed using the result of both as values in a BiFunction, returning a CompletableFuture. |
Combining All |
|
|
Chain two CompletableFuture, when both are completed using the result of both as values in a BiConsumer, returning a value. |
|
Chain two CompletableFuture, when both are completed run a Runnable, returning a CompletableFuture<Void>. |
|
Await the completion of all of a list of CompletableFuture instances, returning a CompletableFuture<Void>. |
Combining Either |
|
|
Accept the completion of the current or other CompletableFuture using the value in a Function, returning a CompletableFuture. |
|
Accept the completion of the current or other CompletableFuture using the value in a Consumer, returning a CompletableFuture. |
|
Accept the completion of the current or other CompletableFuture, then run a Runnable, returning a CompletableFuture<Void>. |
|
Await the completion of any one of a list of CompletableFuture instances, returning a CompletableFuture<Object>. |
CompletionFuture has Stages.
Each Stage may produce an output or signal when completed successfully. Any stage can fail, leading to an exception. The exception can be handled. A handling of an exception may cause the pipeline to be repaired or may be fatal enough to fail.
/----S--o--S--o--S--------------S--o--S--o----SUCCESS
/ \ /
CompletableFuture | |
\ \ /
\-------------------E--h--E--h--E--h----------FAILURE