CountedCompleter Folds Leaf Results
Split an array into forked leaves, fold child results in onCompletion, and read the grand total back through getRawResult after invoke.
Code
import java.util.concurrent.CountedCompleter;
public class ParallelSumLeaves {
// javadoc 的 MapReducer 形状:只 fork 右半,左半在当前线程直接 compute
static class SumTask extends CountedCompleter<Long> {
final long[] data;
final int lo, hi;
SumTask sibling;
Long result;
SumTask(CountedCompleter<?> parent, long[] data, int lo, int hi) {
super(parent);
this.data = data;
this.lo = lo;
this.hi = hi;
}
@Override
public void compute() {
if (hi - lo >= 2) {
int mid = (lo + hi) >>> 1;
SumTask left = new SumTask(this, data, lo, mid);
SumTask right = new SumTask(this, data, mid, hi);
left.sibling = right;
right.sibling = left;
setPendingCount(1);
right.fork();
left.compute();
} else {
result = data[lo]; // 叶子:单元素
tryComplete(); // pending 归零时沿 completer 链向上完成
}
}
@Override
public void onCompletion(CountedCompleter<?> caller) {
if (caller != this) {
SumTask child = (SumTask) caller;
SumTask sib = child.sibling;
if (sib == null || sib.result == null) {
result = child.result;
} else {
result = child.result + sib.result;
}
}
}
@Override
public Long getRawResult() {
return result;
}
}
public static void main(String[] args) {
long[] latencies = {42, 18, 133, 7, 95, 61, 18, 120, 4, 88};
long total = new SumTask(null, latencies, 0, latencies.length).invoke();
System.out.println("sum: " + total);
}
}How the snippet works
The snippet is organized around the classes ParallelSumLeaves and SumTask and the functions compute, onCompletion, getRawResult and main.
What to watch for
- Imports, when present, point only at standard-library modules.
Applying it
The signature doing the main work is public void compute()
Watch for labeled lines in the run — sum: — when the file runs.
Statements that decide the outcome
long total = new SumTask(null, latencies, 0, latencies.length).invoke();
long[] latencies = {42, 18, 133, 7, 95, 61, 18, 120, 4, 88};
tryComplete(); // pending 归零时沿 completer 链向上完成
}
Interactive Tools for This Topic
FAQ
- What does CountedCompleter Folds Leaf Results print when run?
- Invoke the file as-is — the `sum:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.