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
Future
object, aCompletableFuture
object will return a result sometime in future - As the
CompletionStage
object, you can execute more asynchronous tasks after the completion of one or moreCompletableFuture
objects
You can work with a CompletableFuture
class in different ways:
- You can create a
CompletableFuture
object 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
CompletableFuture
class to executeRunnable
orSupplier
with therunAsync()
andsupplyAsync()
methods. These methods will return aCompletableFuture...