Java 8 Parallel Streams
August 15, 2019 Leave a comment
Parallelization is great feature with Java using streams and lambds and can be used to best use of our CPU cores to maximize the calculation.
- parallelStream() -> On collections
- parallel() -> on Streams
But are we sure that we need parallel always, yes, think again?
- Do you have enough size of collation to do parallel operation?
- Why you need parallel? If there are blocking tasks involve in parallel operation like network calls, you may possibly consume all threads in wait state and may impact other parallel operations.
- Here is the key, all parallel streams use same thread pool (create one time) for all parallel operations. You are not going to get new thread pool for each parallel operation. If you block all threads in a pool, other parallel operations will also starving for getting thread and potentially slow down all applications.
- If you know there are chances to have thread lock down condition, can we use our own Thread Executor for each parallel stream (rather than using internally provided).
A information is provided here: http://coopsoft.com/ar/Calamity2Article.html
Case 1 (Shared Fork Join Thread Pool):
Stream<Long> parallelStream = aList.parallelStream();
Case 2: (My own Thread Pool)
ForkJoinPool myPool = new ForkJoinPool(10);
long total= customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
—-





