由CountedCompleter的文档和来源混淆

时间:2015-04-30 11:28:42

标签: java concurrency java.util.concurrent forkjoinpool

这是java.util.concurrent.CountedCompleter类(JDK 1.8.0_25)的代码片段。

/**
 * If the pending count is nonzero, decrements the count;
 * otherwise invokes {@link #onCompletion(CountedCompleter)}
 * and then similarly tries to complete this task's completer,
 * if one exists, else marks this task as complete.
 */
public final void tryComplete() {
    CountedCompleter<?> a = this, s = a;
    for (int c;;) {
        if ((c = a.pending) == 0) {
            a.onCompletion(s);
            if ((a = (s = a).completer) == null) {
                s.quietlyComplete();
                return;
            }
        }
        else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
            return;
    }
}

这让我很困惑。文档说:“然后类似地尝试完成此任务的完成者”,但我没有看到在此任务的完成者上有任何“完成”的调用;或任何其他要求。

有人和这个班级一起工作过吗?这是文档或实现的问题吗?我也可能以错误的方式做饭。任何有关如何正确处理这个课程的想法都表示赞赏。

1 个答案:

答案 0 :(得分:10)

你很困惑吗?每个人都很困惑。我已经对F / J框架进行了四年的批评,我可以告诉你复杂程度达到了8u40的临界水平。这个类存在的原因是因为join()doesn't work。为了绕过Java8流的停滞线程,架构师发明了这个类。

这个类的工作方式是为每个fork()添加addToPendingCount()。在compute()中,完成后,尝试完成()。当计数为零时,该方法调用onCompletion()。有点乱,但如果你的代码很简单,那就有用了。

您看到的其余代码适用于当前的CountedCompleter具有自己的一系列CountedCompleter对象。我的猜测是这可能是parallel.stream处理。