Java Reference
In-Depth Information
its returned price. To do this, you can put all the CompletableFuture<Void>s of the stream into
an array and then wait for the completion of all of them, as in the following listing.
Listing 11.21. Reacting to CompletableFuture completion
CompletableFuture[] futures = findPricesStream("myPhone")
.map(f -> f.thenAccept(System.out::println))
.toArray(size -> new CompletableFuture[size]);
CompletableFuture.allOf(futures).join();
The allOf factory method takes as input an array of CompletableFutures and returns a
CompletableFuture<Void> that's completed only when all the CompletableFutures passed have
completed. This means that invoking join on the CompletableFuture returned by the allOf
method provides an easy way to wait for the completion of all the CompletableFutures in the
original stream. This is useful for the best-price-finder application because it can then display a
message saying “All shops returned results or timed out,” so a user doesn't keep wondering
whether more prices might become available.
Conversely, in other applications you may wish to wait for the completion of only one of the
CompletableFutures in an array, perhaps if you're consulting two currency-exchange servers
and are happy to take the result of the first to respond. In this case, you can similarly use the
anyOf factory method. As a matter of detail, this method takes as input an array of
CompletableFutures and returns a Completable-Future<Object> that completes with the same
value as the first-to-complete CompletableFuture.
11.5.2. Putting it to work
As we discussed at beginning of this section, you'll now suppose that all the methods simulating
a remote invocation will use the randomDelay method of listing 11.19 , introducing a random
delay distributed between 0.5 and 2.5 seconds instead of a delay of 1 second. Running the code
in listing 11.21 with this change, you'll see that the prices provided by the different shops don't
appear all at the same time as happened before but are printed incrementally as soon as the
discounted price for a given shop is available. To make the result of this change more obvious,
we slightly modified the code to report a timestamp showing the time taken for each price to be
calculated:
long start = System.nanoTime();
CompletableFuture[] futures = findPricesStream("myPhone27S")
.map(f -> f.thenAccept(
 
Search WWH ::




Custom Search