Java Reference
In-Depth Information
even how valuable the server regards your application's business compared to other applications
that perhaps pay more per query.
For these reasons it's likely the prices of the products you want to buy will be available for some
shops far earlier than for others. For the purpose of this section, we simulate this scenario in the
following listing by introducing a random delay between 0.5 and 2.5 seconds, using the
randomDelay method instead of the previous delay method that always waited 1 second.
Listing 11.19. A method to simulate a random delay between 0.5 and
2.5 seconds
private static final Random random = new Random();
public static void randomDelay() {
int delay = 500 + random.nextInt(2000);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
Until now, you've implemented the findPrices method so it shows the prices provided by the
different shops only when all of them are available. What you want to do now is have the
best-price-finder application display the price for a given shop as soon as it becomes available,
without waiting for the slowest one (which perhaps even times out). How can you achieve this
further improvement?
11.5.1. Refactoring the best-price-finder application
The first thing to avoid is waiting for the creation of a List already containing all the prices.
You'll need to work directly with the stream of CompletableFutures, where each
CompletableFuture is executing the sequence of operations necessary for a given shop. To do
this, in the next listing you'll refactor the first part of the implementation from listing 11.12 into
a findPricesStream method to produce this stream of CompletableFutures.
 
Search WWH ::




Custom Search