Java Reference
In-Depth Information
The application is spending about the 99% of the time waiting for the shops' responses, so you
could estimate a W/C ratio of 100. This means that if your target is 100% CPU utilization, you
should have a pool with 400 threads. In practice it will be wasteful to have more threads than
shops, because in doing so you'll have threads in your pool that are never used. For this reason,
you need to set up an Executor with a fixed number of threads equal to the number of shops you
have to query, so there will be exactly one thread for each shop. But you must also set an upper
limit of 100 threads in order to avoid a server crash for a larger number of shops, as shown in
the following listing.
Listing 11.12. A custom Executor fitting our best-price-finder application
Note that you're creating a pool made of daemon threads . A Java program can't terminate or
exit while a normal thread is executing, so a leftover thread waiting for a never-satisfiable event
causes problems. By contrast, marking a thread as a daemon means it can be killed on program
termination. There's no performance difference. You can now pass the new Executor as the
second argument of the supplyAsync factory method. For example, you should now create the
CompletableFuture retrieving the price of the requested product from a given shop as follows:
CompletableFuture.supplyAsync(() -> shop.getName() + " price is " +
shop.getPrice(product), executor);
After this improvement, the solution using the CompletableFutures takes only 1021 ms to
process five shops and 1022 ms to process nine. In general this trend carries on until the
number of shops reaches that threshold of 400 we calculated earlier. This demonstrates that it
was a good idea to create an Executor that better fits the characteristics of your application and
to make use of CompletableFutures to submit their tasks to it. This is almost always an effective
strategy and something to consider when making intensive use of asynchronous operations.
Parallelism—via Streams or CompletableFutures?
Search WWH ::




Custom Search