Skip to main content

How do I iterate over a stream using custom thread pool

In this Q&A, we'll go over how to iterate a stream using a custom thread pool

Default behavior of Collection.parallelStream() is to use the common ForkJoin thread pool.  This may lead to resource contention when multiple threads are doing the same thing.  To avoid that, custom fork join pool can be used as below:
ForkJoinPool fjp = new ForkJoinPool(4);
int sum = fjp.submit(() -> l.parallelStream().mapToInt(Integer::intValue).sum() ).get();
System.out.println(sum);

Comments