CKTIS / Java
ForkJoinPool — a pool for tasks split into subtasks
ForkJoinPool executes tasks using work-stealing. Learn synchronous invoke, the shared commonPool, and the lifecycle rules for shutting down an owned pool with shutdown.
Version: Documentation scope: Java SE 21; neither the repository runtime nor the production runtime is attested.
Syntax
new ForkJoinPool(int parallelism)
<T> T ForkJoinPool.invoke(ForkJoinTask<T> task)
static ForkJoinPool ForkJoinPool.commonPool()
void ForkJoinPool.shutdown()ForkJoinPool executes ForkJoinTask tasks using work-stealing: idle threads take available work. It suits computations split into subtasks; blocking I/O can limit progress.
ForkJoinPool.invoke waits for a task's result and propagates its unchecked exceptions or errors. ForkJoinPool.commonPool returns a shared pool; an owned pool separates resource management.
ForkJoinPool.shutdown rejects new tasks in an owned pool while allowing accepted tasks to finish, but does not wait for termination. It does not shut down the common pool. Use awaitTermination to wait after shutdown.
The example sums 1 through 8: fork() makes the left part available, and join() retrieves its result. Documentation scope: Java SE 21; repository runtime and production runtime are not attested.
Examples
import java.util.concurrent.ForkJoinPool;
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 middle = from + (to - from) / 2;
Sum left = new Sum(from, middle);
Sum right = new Sum(middle, to);
left.fork();
int rightResult = right.compute();
return left.join() + rightResult;
}
}
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool(2);
try {
System.out.println(pool.invoke(new Sum(1, 9)));
} finally {
pool.shutdown();
}
}
}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.