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
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
);
}
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