As I know, the parallel streams use the default ForkJoinPool.commonPool
which by default has one less threads than your processors. I want to use my own custom thread pool.
Like this:
@Test
public void stream() throws Exception {
//System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
ForkJoinPool pool = new ForkJoinPool(10);
List<Integer> testList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
long start = System.currentTimeMillis();
List<Integer> result = pool.submit(() -> testList.parallelStream().map(item -> {
try {
// read from database
Thread.sleep(1000);
System.out.println("task" + item + ":" + Thread.currentThread());
} catch (Exception e) {
}
return item * 10;
})).get().collect(Collectors.toList());
System.out.println(result);
System.out.println(System.currentTimeMillis() - start);
}
My custom ForkJoinPool
is never used.
And I change the default parallelism like this:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
It works well - the tasks cost only about 1 second.
In my application the task contains heavy IO operation (reading data from db). So I need higher parallelism, but I do not want to change the JVM property.
So what is the right way to specify my own ForkJoinPool
?
Or how to use parallel streams in IO-intensive situation?