Java Reference
In-Depth Information
Turning to our running example, you may know that one of the shops provides prices in €(EUR),
but you always want to communicate them in $ (USD) to your customers. You can
asynchronously ask the shop the price of a given product and retrieve, from a remote
exchange-rate service, the current exchange rate between € and $. After both have completed,
you can combine the results by multiplying the price by the exchange rate. With this approach,
you'll obtain a third CompletableFuture that will complete when the results of the two
CompletableFutures are both available and have been combined using the BiFunction, as done
in the following listing.
Listing 11.17. Combining two independent CompletableFuture s
Here, because the combination operation is a simple multiplication, performing it in a separate
task would have been a waste of resources, so you need to use the then-Combine method instead
of its asynchronous thenCombineAsync counterpart. Figure 11.6 shows how the different tasks
created in listing 11.17 are executed on the different threads of the pool and how their results are
combined.
 
Search WWH ::




Custom Search