问题
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