Custom thread pool in Java 8 parallel stream

后端 未结 15 925
旧巷少年郎
旧巷少年郎 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 01:03

    If you don't want to rely on implementation hacks, there's always a way to achieve the same by implementing custom collectors that will combine map and collect semantics... and you wouldn't be limited to ForkJoinPool:

    list.stream()
      .collect(parallelToList(i -> fetchFromDb(i), executor))
      .join()
    

    Luckily, it's done already here and available on Maven Central: http://github.com/pivovarit/parallel-collectors

    Disclaimer: I wrote it and take responsibility for it.

提交回复
热议问题