Confused by docs and source of CountedCompleter

隐身守侯 提交于 2019-12-24 04:09:28

问题


Here is a code fragment of java.util.concurrent.CountedCompleter class (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;
    }
}

It makes me really confused. The documentation says: "and then similarly tries to complete this task's completer", but I do not see any invocations of 'complete' on this task's completer; or any other calls to it.

Have anybody worked with this class? Is it an issue with documentation or implementation? I might also cook it in a wrong way. Any ideas how to properly deal with this class is appreciated.


回答1:


You're confused? Everyone is confused. I've been writing a critique on the F/J framework for four years now and I can tell you the level of complexity is reaching the critical level with 8u40. The reason this class exists at all is because the join() doesn't work. In order to get around the stalling threads for Java8 streams the architect invented this class.

The way you work this class is you addToPendingCount() for every fork(). In the compute(), when done, you tryComplete(). When the count is zero, the method calls your onCompletion(). A bit messy but if your code is simple, it works.

The rest of the code you see is for when the current CountedCompleter has a chain of CountedCompleter objects of its own. My guess is this is probably for the parallel.stream processing.



来源:https://stackoverflow.com/questions/29966535/confused-by-docs-and-source-of-countedcompleter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!