CKTIS / Java
ForkJoinTask — splitting computations and combining results
ForkJoinTask represents a task executed by ForkJoinPool. Learn scheduling with fork(), retrieving results with join(), and group execution with invokeAll() through an example that splits a sum into subtasks.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
ForkJoinTask<V> task;
ForkJoinTask<V> scheduled = task.fork();
V result = task.join();
ForkJoinTask.invokeAll(task1, task2);ForkJoinTask<V> is an abstract task for ForkJoinPool. For computations returning a result, usually extend RecursiveTask<V> and implement compute(). The pool shares threads among tasks; a task does not imply a separate thread.
ForkJoinTask.fork() schedules execution in the current pool, or in ForkJoinPool.commonPool() outside one. ForkJoinTask.join() waits for the result; it does not throw InterruptedException and propagates failures as unchecked exceptions.
ForkJoinTask.invokeAll() starts a group of tasks and waits for completion or an exception. After an exception, other tasks may be cancelled; completion of every task is not guaranteed. Retrieve results with join().
Avoid blocking I/O and cyclic task dependencies. In the example, pool.invoke(root) starts the computation in a dedicated pool. Sum splits a range in half, computes one half locally, and combines results; invokeAll() coordinates two parts. The small splitting threshold is for demonstration, not performance measurement.
Examples
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
public class Main {
static final class Sum extends RecursiveTask<Integer> {
private final int from;
private final int to;
Sum(int from, int to) {
this.from = from;
this.to = to;
}
@Override
protected Integer compute() {
if (to - from <= 2) {
int total = 0;
for (int i = from; i < to; i++) {
total += i;
}
return total;
}
int mid = from + (to - from) / 2;
Sum left = new Sum(from, mid);
Sum right = new Sum(mid, to);
left.fork();
int rightResult = right.compute();
return left.join() + rightResult;
}
}
public static void main(String[] args) {
try (ForkJoinPool pool = new ForkJoinPool(2)) {
ForkJoinTask<Integer> root = new RecursiveTask<Integer>() {
@Override
protected Integer compute() {
Sum first = new Sum(1, 5);
Sum second = new Sum(5, 9);
ForkJoinTask.invokeAll(first, second);
return first.join() + second.join();
}
};
System.out.println(pool.invoke(root));
}
}
}Result
36
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.