Java Reference
In-Depth Information
NOTE
You might have encountered the concept behind the
CompletableFuture
before; various
other languages call them a
deferred object
or a
promise
. In the Google Guava Library
and the Spring Framework these are referred to as
ListenableFuture
s.
Example 9-10. Downloading album information from some external web services using
CompletableFutures
public
public
Album
lookupByName
(
String albumName
) {
CompletableFuture
<
List
<
Artist
>>
artistLookup
=
loginTo
(
"artist"
)
.
thenCompose
(
artistLogin
->
lookupArtists
(
albumName
,
artistLogin
));
return
return
loginTo
(
"track"
)
.
thenCompose
(
trackLogin
->
lookupTracks
(
albumName
,
trackLogin
))
.
thenCombine
(
artistLookup
, (
tracks
,
artists
)
->
new
new
Album
(
albumName
,
tracks
,
artists
))
.
join
();
}
pletableFuture
instead of a
Future
. The key “trick” to the
CompletableFuture
API is to
register lambda expressions and chain higher-order functions. The methods are different, but
the concept is incredibly similar to the Streams API design.
At we use the
thenCompose
method to transform our
Credentials
into a
Com-
pletableFuture
that contains the artists. This is a bit like taking an IOU for money from a
friend and spending the money on Amazon when you get it. You don't immediately get a
new topic—you just get an email from Amazon saying that your topic is on its way: a differ-
ent form of IOU.
At we again use
thenCompose
and the
Credentials
from our Track API login in order to
generate a
CompletableFuture
of tracks. We introduce a new method,
thenCombine
, at .
This takes the result from a
CompletableFuture
and combines it with another
Com-
pletableFuture
. The combining operation is provided by the end user as a lambda expres-