Java Reference
In-Depth Information
Listing 11.9. Checking findPrices correctness and performance
long start = System.nanoTime();
System.out.println(findPrices("myPhone27S"));
long duration = (System.nanoTime() - start) / 1_000_000;
System.out.println("Done in " + duration + " msecs");
The code in listing 11.9 produces output like this:
[BestPrice price is 123.26, LetsSaveBig price is 169.47, MyFavoriteShop price is 214.13, BuyItAll
price is 184.74]
Done in 4032 msecs
As you may have expected, the time taken by the findPrices method to run is just a few
milliseconds longer than 4 seconds, because the four shops are queried sequentially and
blocking one after the other, and each of them takes 1 second to calculate the price of the
requested product. How can you improve on this result?
11.3.1. Parallelizing requests using a parallel Stream
After reading chapter 7 , the first and quickest improvement that should occur to you would be to
avoid this sequential computation using a parallel Stream instead of a sequential, as shown in
the next listing.
Listing 11.10. Parallelizing the findPrices method
Find out if this new version of findPrices is any better by again running the code in listing 11.9 :
[BestPrice price is 123.26, LetsSaveBig price is 169.47, MyFavoriteShop price is 214.13, BuyItAll
price is 184.74]
Done in 1180 msecs
 
Search WWH ::




Custom Search