Customizing parallelStream's thread pool
Introduction
By default, ForkJoinPool creates a thread for each processor, and parallelStream will use this shared thread pool to submit tasks if not specified.
So how do we handle a specific situation where we want to use a custom ForkJoinPool?
Common operations
If we want to do an addition from 1 to 1000, we can use parallel stream like this.
List<Integer> integerList= IntStream.range(1,1000).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
Integer total= integerList.parallelStream().reduce(0, Integer::sum);
log.info("{}",total);
Output result.
INFO com.javaisland.CustThreadPool - 499500
Using a custom ForkJoinPool
The above example uses a shared thread pool. Let’s look at how to use a custom thread pool to commit a parallel stream:
List<Integer> integerList= IntStream.range(1,1000).boxed().collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
Integer actualTotal = customThreadPool.submit(
() -> integerList.parallelStream().reduce(0, Integer::sum)).get();
log.info("{}",actualTotal);
In the above example, we defined a ForkJoinPool with 4 threads and used it to submit this parallelStream.
Output result.
INFO com.javaisland.CustThreadPool - 499500
Summary
If you don’t want to use a public thread pool, you can use a custom ForkJoinPool to submit it.