Java Reference
In-Depth Information
sion. We want to take our tracks and artists and build up an Album object, so that's what we
do.
At this point, it's worth reminding yourself that just like with the Streams API, we're not ac-
tually doing things; we're building up a recipe that says how to do things. Our method can't
guarantee that the CompletableFuture has completed until one of the final methods is
called. Because CompletableFuture implements Future , we could just call the get method
again. CompletableFuture contains the join method, which is called at and does the
same job. It doesn't have a load of the nasty checked exceptions that hindered our use of get .
You've probably got the basic idea of how to use CompletableFuture , but creating them is
another matter. There are two different aspects of creating a CompletableFuture : creating
the object itself and actually completing it by giving it the value that it owes its client code.
As Example 9-11 shows, it's pretty easy to create a CompletableFuture object. You just call
its constructor! This object can now be handed out to client code for chaining operations. We
also keep a reference to this object in order to process the work on another thread.
Example 9-11. Completing a future by providing a value
CompletableFuture < Artist > createFuture ( String id ) {
CompletableFuture < Artist > future = new
new CompletableFuture <>();
startJob ( future );
return
return future ;
}
Once we've performed the work that needs to be done on whatever thread we're using, we
need to tell the CompletableFuture what value it represents. Remember that this work can
by done through a number of different threading models. For example, we can submit a task
to an ExecutorService , use an event loop-based system such as Vert.x, or just spin up a
Thread and do work on it. As shown in Example 9-12 , in order to tell the CompletableFu-
ture that it's ready, you call the complete method. It's time to pay back the IOU.
Example 9-12. Completing a future by providing a value
future . complete ( artist );
 
Search WWH ::




Custom Search