ForkJoin RecursiveTask Parallel Sum
Split an array range recursively and fork one half so ForkJoinPool threads compute partial sums in parallel, then join the halves into the total.
Code
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ParallelSum extends RecursiveTask<Long> {
private static final int THRESHOLD = 4;
private final long[] numbers;
private final int from;
private final int to;
ParallelSum(long[] numbers, int from, int to) {
this.numbers = numbers;
this.from = from;
this.to = to;
}
@Override
protected Long compute() {
if (to - from <= THRESHOLD) {
long sum = 0;
for (int i = from; i < to; i++) sum += numbers[i];
return sum;
}
int mid = (from + to) >>> 1;
ParallelSum left = new ParallelSum(numbers, from, mid);
ParallelSum right = new ParallelSum(numbers, mid, to);
left.fork(); // 左半异步入队
long rightResult = right.compute(); // 右半当前线程递归执行
long leftResult = left.join(); // 等左半完成再合并
return leftResult + rightResult;
}
public static void main(String[] args) {
long[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
long total = ForkJoinPool.commonPool()
.invoke(new ParallelSum(numbers, 0, numbers.length));
System.out.println("total = " + total);
}
}Inside the snippet
The working surface is the class ParallelSum and the functions compute and main — everything else is wiring.
The file repeats itself only inside for (int i = from; i < to; i++) sum += numbers[i];.
Putting it to use
The main signature reads protected Long compute()
The demo output is labeled (total =), so every printed line maps back to its originating operation.
Core lines
for (int i = from; i < to; i++) sum += numbers[i];
return leftResult + rightResult;
Interactive Tools for This Topic
FAQ
- What does ForkJoin RecursiveTask Parallel Sum print when run?
- Execute the whole file; each printed line is prefixed with a label like `total =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.