Java Reference
In-Depth Information
Listing 11.18. Combining two Future s in Java 7
In listing 11.18 , you create a first Future, submitting a Callable to an Executor querying an
external service to find the exchange rate between EUR and USD. Then you create a second
Future, retrieving the price in EUR of the requested product for a given shop. Finally, as you did
in listing 11.17 , you multiply the exchange rate by the price in the same future that also queried
the shop to retrieve the price in EUR. Note that using thenCombineAsync instead of
thenCombine in listing 11.17 would have been equivalent to performing the price by rate
multiplication in a third Future in listing 11.18 . The difference between these two
implementations might seem small, but this is because you're just combining two Futures.
Listings 11.19 and 11.20 show how easy it is to create a pipeline that mixes synchronous and
asynchronous operations, and the advantages of this declarative style are more evident when the
number of tasks to be performed and results to be combined increases.
You're almost finished with your best-price-finder application, but there's still one ingredient
missing. You'd like to show your users the prices provided by the different shops as soon as they
become available (car insurance or flight-comparison websites typically do this), instead of
waiting for all the price requests to complete, as you did until now. In the next section, you'll
discover how to achieve this by reacting to the completion of a CompletableFuture instead of
invoking get or join on it and thereby remaining blocked until the CompletableFuture itself
completes.
11.5. Reacting to a CompletableFuture completion
In all the code examples you've seen in this chapter, you simulated methods doing remote
invocations with a 1-second delay in their response. Nevertheless, in a real-world scenario, the
various remote services you need to contact from your application are likely to have
unpredictable delays, caused by everything from server load to network delays, and perhaps
 
Search WWH ::




Custom Search