Java Reference
In-Depth Information
called as an alternative to complete . You shouldn't call both complete and completeEx-
ceptionally on a CompletableFuture , though.
Example 9-14. Completing a future if there's an error
future . completeExceptionally ( new
new AlbumLookupException ( "Unable to find " + name ));
A complete investigation of the CompletableFuture API is rather beyond the scope of this
chapter, but in many ways it is a hidden goodie bag. There are quite a few useful methods in
the API for composing and combining different instances of CompletableFuture in pretty
much any way imaginable. Besides, by now you should be familiar with the fluent style of
chaining sequences of higher-order functions to tell the computer what to do.
Let's take a brief look at a few of those use cases:
▪ If you want to end your chain with a block of code that returns nothing, such as a Con-
sumer or Runnable , then take a look at thenAccept and thenRun .
▪ Transforming the value of the CompletableFuture , a bit like using the map method on
Stream , can be achieved using thenApply .
▪ If you want to convert situations in which your CompletableFuture has completed with
an exception, the exceptionally method allows you to recover by registering a function
to make an alternative value.
▪ If you need to do a map that takes account of both the exceptional case and regular use
cases, use handle .
▪ When trying to figure out what is happening with your CompletableFuture , you can use
the isDone and isCompletedExceptionally methods.
CompletableFuture is really useful for building up concurrent work, but it's not the only
game in town. We're now going to look at a related concept that offers a bit more flexibility
in exchange for more complex code.
Reactive Programming
The concept behind a CompletableFuture can be generalized from single values to com-
plete streams of data using reactive programming . Reactive programming is actually a form
Search WWH ::




Custom Search