Java Reference
In-Depth Information
blocked on a single request and thereby increasing the performance and the throughput of your
best-price-finder application.
11.3. Make your code non-blocking
So you've been asked to develop a best-price-finder application, and all the shops you have to
query provide only the same synchronous API implemented as shown at the beginning of
section 11.2 . In other words, you have a list of shops, like this one:
List<Shop> shops = Arrays.asList(new Shop("BestPrice"),
new Shop("LetsSaveBig"),
new Shop("MyFavoriteShop"),
new Shop("BuyItAll"));
You have to implement a method with the following signature, that given the name of a product
returns a List of strings, where each string contains the name of a shop and the price of the
requested product in that shop:
public List<String> findPrices(String product);
Your first idea will probably be to use the Stream features you learned in chapters 4 , 5 , and 6 .
You may be tempted to write something like what's shown in the next listing (yes, it's good if
you're already thinking this first solution is bad!).
Listing 11.8. A findPrices implementation sequentially querying all the
shops
public List<String> findPrices(String product) {
return shops.stream()
.map(shop -> String.format("%s price is %.2f",
shop.getName(), shop.getPrice(product)))
.collect(toList());
}
Okay, this was straightforward. Now try to put the method findPrices to work with the only
product you want madly these days (yes, you guessed it; it's the myPhone27S). In addition,
record how long the method takes to run, as shown in the following listing; this will let you
compare its performance with the improved method we develop later.
 
Search WWH ::




Custom Search