Java Reference
In-Depth Information
Figure 9-4. A completable future is an IOU that can be processed by handlers
Of course, a very common usage of CompletableFuture is to asynchronously run a block of
code. This code completes and returns a value. In order to avoid lots of people having to im-
plement the same code over and over again, there is a useful factory method for creating a
CompletableFuture , shown in Example 9-13 , called supplyAsync .
Example 9-13. Example code for asynchronously creating a CompletableFuture
CompletableFuture < Track > lookupTrack ( String id ) {
return
return CompletableFuture . supplyAsync (() -> {
// Some expensive work is done here
// ...
return
return track ;
}, service );
}
The supplyAsync method takes a Supplier that gets executed. The key point, shown at ,
is that this Supplier can do some time-consuming work without blocking the current
thread—thus the Async in the method name. The value returned at is used to complete the
CompletableFuture . At we provide an Executor , called service , that tells the Com-
pletableFuture where to perform the work. If no Executor is provided, it just uses the
same fork/join thread pool that parallel streams execute on.
Of course, not every IOU has a happy ending. Sometimes we encounter exceptional circum-
stances and can't pay our debts. As Example 9-14 demonstrates, the CompletableFuture
API accounts for these situations by letting you completeExceptionally . This can be
 
Search WWH ::




Custom Search