Custom thread pool in Java 8 parallel stream

后端 未结 15 913
旧巷少年郎
旧巷少年郎 2020-11-22 00:15

Is it possible to specify a custom thread pool for Java 8 parallel stream? I can not find it anywhere.

Imagine that I have a server application and I would like to

15条回答
  •  长情又很酷
    2020-11-22 00:58

    Until now, I used the solutions described in the answers of this question. Now, I came up with a little library called Parallel Stream Support for that:

    ForkJoinPool pool = new ForkJoinPool(NR_OF_THREADS);
    ParallelIntStreamSupport.range(1, 1_000_000, pool)
        .filter(PrimesPrint::isPrime)
        .collect(toList())
    

    But as @PabloMatiasGomez pointed out in the comments, there are drawbacks regarding the splitting mechanism of parallel streams which depends heavily on the size of the common pool. See Parallel stream from a HashSet doesn't run in parallel .

    I am using this solution only to have separate pools for different types of work but I can not set the size of the common pool to 1 even if I don't use it.

提交回复
热议问题