java - 如何确定fork-join任务的合适分工阈值

标签 java concurrency fork-join

看了Fork/Join Tutorial之后,我创建了一个用于计算大阶乘的类:

public class ForkFactorial extends RecursiveTask<BigInteger> {

    final int end;
    final int start;
    private static final int THRESHOLD = 10;

    public ForkFactorial(int n) {
        this(1, n + 1);
    }

    private ForkFactorial(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected BigInteger compute() {
        if (end - start < THRESHOLD) {
            return computeDirectly();
        } else {
            int mid = (start + end) / 2;
            ForkFactorial lower = new ForkFactorial(start, mid);
            lower.fork();
            ForkFactorial upper = new ForkFactorial(mid, end);
            BigInteger upperVal = upper.compute();
            return lower.join().multiply(upperVal);
        }
    }

    private BigInteger computeDirectly() {
        BigInteger val = BigInteger.ONE;
        BigInteger mult = BigInteger.valueOf(start);
        for (int iter = start; iter < end; iter++, mult = mult.add(BigInteger.ONE)) {
            val = val.multiply(mult);
        }
        return val;
    }
}

我的问题是如何确定我分割任务的阈值?我找到了一个 page on fork/join parallelism其中指出:

One of the main things to consider when implementing an algorithm using fork/join parallelism is chosing the threshold which determines whether a task will execute a sequential computation rather than forking parallel sub-tasks.

If the threshold is too large, then the program might not create enough tasks to fully take advantage of the available processors/cores.

If the threshold is too small, then the overhead of task creation and management could become significant.

In general, some experimentation will be necessary to find an appropriate threshold value.

那么我需要做哪些实验才能确定阈值?

最佳答案

PigeonHole估计:设置一个任意的Threshold,计算计算时间。 并根据它增加和减少阈值以查看您的计算时间是否有所改善,直到您通过降低阈值看不到任何改善。

关于java - 如何确定fork-join任务的合适分工阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20177364/

相关文章:

java - finishActivity() 在 Android 中未按预期工作

java - 如何制作字符数组扫描仪?

java - 将一个 Java 对象引用替换为另一个被认为是线程安全的对象引用,还是我忽略了潜在的同步性问题?

java - 为什么静态初始化程序中带有 lambda 的并行流会导致死锁?

Java ForkJoinPool 未利用所有 CPU 核心

java - 使用 java 8 stream api 做数组列表的深层复制但得到构建时间错误

java - 根据 DateTime 行对 HashBasedTable 条目进行分组

java - 在 Berkeley DB JE 中进行比较和交换?

c# - 传递给在紧密循环中生成的线程的参数

Java Fork-Join 不适用于大型 ArrayList