← 中文资源

简体中文版本

专用 ForkJoinPool 隔离并行流

把并行流提交进专用 ForkJoinPool 而不是 common pool:重聚合不再占用公共线程池,try-with-resources 保证池最终关闭。

阅读英文原文

实现说明

专用 ForkJoinPool 隔离并行流的核心是类 IsolatedParallelSum和函数 main。 try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。

使用要点

  • 跑完文件,输出里会留下标记——custom pool parallelism:、sum of squares:。

常见问题

运行「专用 ForkJoinPool 隔离并行流」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 custom pool parallelism:、sum of squares: 标签标明各步骤。

核心语句

.map(n -> n * n)
.sum()).join();

代码示例

import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;

public class IsolatedParallelSum {

    public static void main(String[] args) {
        // parallel streams borrow the common pool by default: an explicit dedicated pool isolates the heavy aggregation
        long total;
        try (ForkJoinPool customPool = new ForkJoinPool(4)) {
            total = customPool.submit(() ->
                    LongStream.rangeClosed(1, 100_000).parallel()
                            .map(n -> n * n)
                            .sum()).join();
            System.out.println("custom pool parallelism: " + customPool.getParallelism());
        }
        System.out.println("sum of squares: " + total);
    }
}