Java Reference
In-Depth Information
Caused by: java.lang.RuntimeException: product not available
at lambdasinaction.chap11.AsyncShop.calculatePrice(AsyncShop.java:36)
at lambdasinaction.chap11.AsyncShop.lambda$getPrice$0(AsyncShop.java:23)
at lambdasinaction.chap11.AsyncShop$$Lambda$1/24071475.run(Unknown Source)
at java.lang.Thread.run(Thread.java:744)
Creating a CompletableFuture with the supplyAsync factory method
Until now you've created CompletableFutures and completed them programmatically, when it
seemed convenient to do so, but the CompletableFuture class itself comes with lots of handy
factory methods that can make this process far easier and less verbose. For example, the
supplyAsync method can let you rewrite the getPriceAsync method in listing 11.4 with a single
statement, as shown in the following listing.
Listing 11.7. Creating a CompletableFuture with the supplyAsync factory
method
public Future<Double> getPriceAsync(String product) {
return CompletableFuture.supplyAsync(() -> calculatePrice(product));
}
The supplyAsync method accepts a Supplier as argument and returns a Completable-Future that
will be asynchronously completed with the value obtained by invoking that Supplier. This
Supplier will be run by one of the Executors in the ForkJoinPool, but you can specify a different
Executor by passing it as a second argument to the overloaded version of this method. More
generally, it's possible to optionally pass an Executor to all other CompletableFuture factory
methods, and you'll use this capability in section 11.3.4 , where we demonstrate that using an
Executor that fits the characteristics of your application can have a positive effect on its
performance.
Also note that the CompletableFuture returned by the getPriceAsync method in listing 11.7 is
totally equivalent to the one you created and completed manually in listing 11.6 , meaning it
provides the same error management you carefully added.
For the rest of this chapter, we'll suppose you sadly have no control over the API implemented
by the Shop class and that it provides only synchronous blocking methods. This is also what
typically happens when you want to consume an HTTP API provided by some service. You'll
learn how it's still possible to query multiple shops asynchronously, thus avoiding becoming
 
Search WWH ::




Custom Search