Java Reference
In-Depth Information
You extract the value of the Future by calling its get method, which blocks until the value is
ready. Unfortunately, Future s end up with composability issues, just like callbacks. We'll
take a quick look at the issues that you can encounter.
The scenario we'll be considering is looking up information about an Album from some ex-
ternal web services. We need to find the list of tracks associated with a given Album and also
a list of artists. We also need to ensure that we have sufficient credentials to access each of
the services. So we need to log in, or at least make sure that we're already logged in.
Example 9-9 is an implementation of this problem using the existing Future API. We start
out at by logging into the track and artist services. Each of these login actions returns a
Future<Credentials> object with the login information. The Future interface is generic,
so Future<Credentials> can be read as an IOU for a Credentials object.
Example 9-9. Downloading album information from some external web services using Fu-
tures
@Override
public
public Album lookupByName ( String albumName ) {
Future < Credentials > trackLogin = loginTo ( "track" );
Future < Credentials > artistLogin = loginTo ( "artist" );
try
try {
Future < List < Track >> tracks = lookupTracks ( albumName , trackLogin . get ());
Future < List < Artist >> artists = lookupArtists ( albumName , artistLogin . get ());
return
return new
new Album ( albumName , tracks . get (), artists . get ());
} catch
catch ( InterruptedException | ExecutionException e ) {
throw
throw new
new AlbumLookupException ( e . getCause ());
}
}
At we make our calls to look up the tracks and artists given the login credentials and call
get on both of these login credentials in order to get them out of the Future s. At we build
up our new Album to return, again calling get in order to block on the existing Future s. If
there's an exception, it gets thrown, so we have to propagate it through a domain exception at
.
As you'll have noticed, if you want to pass the result of one Future into the beginning of an-
other piece of work, you end up blocking the thread of execution. This can be become a per-
formance limitation because instead of work being executed in parallel it is (accidentally) run
in serial.
 
 
Search WWH ::




Custom Search