Java Reference
In-Depth Information
result of the first as input for its computation. Note that with this approach, while the Futures
are retrieving the quotes from the different shops, the main thread can perform other useful
operations such as responding to UI events.
Collecting the elements of the Stream resulting from these three map operations into a List, you
obtain a List<CompletableFuture<String>>, and finally you can wait for the completion of those
CompletableFutures and extract their values using join, exactly as you did in listing 11.11 . This
new version of the findPrices method implemented in listing 11.8 might produce output like
this:
[BestPrice price is 110.93, LetsSaveBig price is 135.58, MyFavoriteShop price is 192.72, BuyItAll
price is 184.74, ShopEasy price is 167.28]
Done in 2035 msecs
The thenCompose method you used in listing 11.16 , like other methods of the
Completable-Future class, also has a variant with an Async suffix, thenComposeAsync. In
general, a method without the Async suffix in its name executes its task in the same thread as
the previous task, whereas a method terminating with Async always submits the succeeding task
to the thread pool, so each of the tasks can be handled by a different thread. In this case, the
result of the second CompletableFuture depends on the first, so it makes no difference to the
final result or to its broad-brush timing whether you compose the two CompletableFutures with
one or the other variant of this method. We chose to use the one with thenCompose only
because it's slightly more efficient due to less thread-switching overhead.
11.4.4. Combining two CompletableFutures—dependent and
independent
In listing 11.16 , you invoked the thenCompose method on one CompletableFuture and passed to
it a second CompletableFuture, which needed as input the value resulting from the execution of
the first. But another frequently occurring case is where you need to combine the results of the
operations performed by two completely independent CompletableFutures, and you don't want
to wait for the first to complete before starting on the second.
In situations like this, use the thenCombine method; this takes as second argument a
BiFunction, which defines how the results of the two CompletableFutures are to be combined
when they both become available. Just like thenCompose, the thenCombine method also comes
with an Async variant. In this case, using the thenCombineAsync method will cause the
combination operation defined by the BiFunction to be submitted to the thread pool and then
executed asynchronously in a separate task.
 
Search WWH ::




Custom Search