Java Reference
In-Depth Information
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.
I'll illustrate some usage scenarios by rewriting Example 9-9 to use CompletableFuture ,
rather than Future , as in Example 9-10 .
Example 9-10. Downloading album information from some external web services using
public Album lookupByName ( String albumName ) {
CompletableFuture < List < Artist >> artistLookup
= loginTo ( "artist" )
. thenCompose ( artistLogin -> lookupArtists ( albumName , artistLogin ));
return loginTo ( "track" )
. thenCompose ( trackLogin -> lookupTracks ( albumName , trackLogin ))
. thenCombine ( artistLookup , ( tracks , artists )
-> new
new Album ( albumName , tracks , artists ))
. join ();
In Example 9-10 loginTo , lookupArtists , and lookupTracks all return a Com-
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-
Search WWH ::

Custom Search