Java Reference
In-Depth Information
Given a collection containing a series of integers, the following code will calculate the stock
price history for the symbol corresponding to the given integer:
Stream < Integer > stream = arrayList . parallelStream ();
stream . forEach ( a -> {
String symbol = StockPriceUtils . makeSymbol ( a );
StockPriceHistory sph = new
new StockPriceHistoryImpl ( symbol , startDate ,
endDate , entityManager );
});
This code will calculate the mock price histories in parallel: the forEach() method will cre-
ate a task for each element in the array list, and each task will be processed by the common
ForkJoinTask pool. That is functionally equivalent to the test at the beginning of this
chapter, where a thread pool was used to calculate the histories in parallel (though this code
is much easier to write than dealing with the thread pool explicitly).
Sizing the common ForkJoinTask pool is as important as sizing any other thread pool. By
default, the common pool will have as many threads as the target machines has CPUs. If you
are running multiple JVMs on the same machine, limiting that number makes sense so that
the JVMs do not compete for CPU against each other. Similarly, if servlet code will execute
a parallel task and you want to make sure that CPU is available for other tasks, consider
lowering the size of the common pool. Or if tasks in the common pool will block waiting for
I/O or other data, the common pool size might need to be increased.
The size can be set by specifying the system property -
Djava.util.concurrent.ForkJoinPool.common.parallelism= N .
Earlier in this chapter, Table 9-1 showed the effect on the performance of the parallel stock
history calculations when the pool had various sizes. Table 9-7 compares that data to the
forEach() construct using the common ForkJoinPool (with the parallelism system prop-
erty set to the given value).
Search WWH ::




Custom Search