Java Reference
In-Depth Information
s -> System.out.println(s + " (done in " +
((System.nanoTime() - start) / 1_000_000) + " msecs)")))
.toArray(size -> new CompletableFuture[size]);
CompletableFuture.allOf(futures).join();
System.out.println("All shops have now responded in "
+ ((System.nanoTime() - start) / 1_000_000) + " msecs");
Running this code produces output similar to the following:
BuyItAll price is 184.74 (done in 2005 msecs)
MyFavoriteShop price is 192.72 (done in 2157 msecs)
LetsSaveBig price is 135.58 (done in 3301 msecs)
ShopEasy price is 167.28 (done in 3869 msecs)
BestPrice price is 110.93 (done in 4188 msecs)
All shops have now responded in 4188 msecs
You can see that, due to the effect of the random delays, the first price is now printed more than
twice as fast as the last!
11.6. Summary
In this chapter, you learned the following:
Executing relatively long-lasting operations using asynchronous tasks can increase the performance
and responsiveness of your application, especially if it relies on one or more remote external services.
You should consider providing an asynchronous API to your clients. You can easily implement it using
CompletableFuture s features.
A CompletableFuture also allows you to propagate and manage errors generated within an
asynchronous task.
You can asynchronously consume from a synchronous API by simply wrapping its invocation in a
CompletableFuture .
You can compose or combine multiple asynchronous tasks both when they're independent and when
the result of one of them is used as the input to another.
You can register a callback on a CompletableFuture to reactively execute some code when the
Future completes and its result becomes available.
You can determine when all values in a list of CompletableFuture s have completed, or alternatively
you can wait for just the first to complete.
 
Search WWH ::




Custom Search