Completing and linking tasks asynchronously
Java 8 Concurrency API includes a new synchronization mechanism with the CompletableFuture class. This class implements the Future object and the CompletionStage interface that gives it the following two characteristics:
- As the
Futureobject, aCompletableFutureobject will return a result sometime in future - As the
CompletionStageobject, you can execute more asynchronous tasks after the completion of one or moreCompletableFutureobjects
You can work with a CompletableFuture class in different ways:
- You can create a
CompletableFutureobject explicitly and use it as a synchronization point between tasks. One task will establish the value returned byCompletableFuture, using thecomplete()method, and the other tasks will wait for this value, using theget()orjoin()methods. - You can use a static method of the
CompletableFutureclass to executeRunnableorSupplierwith therunAsync()andsupplyAsync()methods. These methods will return aCompletableFuture...