Why does stream parallel() not use all available threads?

后端 未结 2 815
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 12:30

I tried to run 100 Sleep tasks in parallel using Java8(1.8.0_172) stream.parallel() submitted inside a custom ForkJoinPool with 100+ threads available. Each

2条回答
  •  青春惊慌失措
    2021-01-07 13:14

    Since the Stream implementation’s use of the Fork/Join pool is an implementation detail, the trick to force it to use a different Fork/Join pool is undocumented as well and seems to work by accident, i.e. there’s a hardcoded constant determining the actual parallelism, depending on the default pool’s parallelism. So using a different pool was not foreseen, originally.

    However, it has been recognized that using a different pool with an inappropriate target parallelism is a bug, even if this trick is not documented, see JDK-8190974.

    It has been fixed in Java 10 and backported to Java 8, update 222.

    So a simple solution world be updating the Java version.

    You may also change the default pool’s parallelism, e.g.

    System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "100");
    

    before doing any Fork/Join activity.

    But this may have unintended effects on other parallel operations.

提交回复
热议问题