ForkJoinPool
ForkJoinPool is a thread pool for divide-and-conquer tasks. Workers steal work from each other. Parallel streams and CompletableFuture default async stages use the common pool.
Detailed Explanation
A fork-join task splits a large job into pieces, forks the pieces, and joins the results. RecursiveTask<V> returns a value. RecursiveAction does not. You fork() a subtask, compute the other half, then join(). The pool's work-stealing queues keep cores busy when splits are uneven.
The common pool (ForkJoinPool.commonPool()) is shared. Its parallelism defaults to Runtime.availableProcessors() - 1 (at least 1). Parallel streams, Arrays.parallelSort, and CompletableFuture.supplyAsync without an executor all share it. Blocking inside those tasks starves unrelated code.
You can construct a private ForkJoinPool and pool.invoke(task) or pool.submit. In Java 21+, ForkJoinPool also supports some virtual-thread experiments, but the mental model remains: CPU-bound, fine-grained, non-blocking tasks.
You reach for fork-join when a problem splits cleanly (sort, parallel sum, tree walk) and subtasks are CPU-heavy enough to beat the split cost. You reach for a fixed ExecutorService for I/O and for mixed blocking work. You reach for virtual threads for many blocking tasks.
The cost of a threshold that is too small is more task objects than useful work. The cost of a threshold that is too large is idle cores. A few thousand elements per leaf is a common starting point. The cost of join in the wrong order can still deadlock in custom graphs; stick to the fork-compute-join pattern.
ManagedBlocker tells the pool a worker is about to block so it may start a spare thread. Prefer not blocking. Never run a parallel stream inside another parallel stream on the common pool without knowing you will compete with yourself.
Code Examples
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class Sum extends RecursiveTask<Long> {
private final int[] xs;
private final int lo;
private final int hi;
Sum(int[] xs, int lo, int hi) {
this.xs = xs;
this.lo = lo;
this.hi = hi;
}
@Override
protected Long compute() {
if (hi - lo <= 4) {
long s = 0;
for (int i = lo; i < hi; i++) {
s += xs[i];
}
return s;
}
int mid = (lo + hi) >>> 1;
Sum left = new Sum(xs, lo, mid);
left.fork();
long right = new Sum(xs, mid, hi).compute();
return left.join() + right;
}
public static void main(String[] args) {
int[] xs = {1, 2, 3, 4, 5, 6, 7, 8};
long sum = ForkJoinPool.commonPool().invoke(new Sum(xs, 0, xs.length));
System.out.println(sum); // prints: 36
}
}Common Gotchas
Blocking on the common pool starves parallel streams and default futures
use a private executor for I/O.
Parallelism is cores, not "as many tasks as I have"
extra tasks queue.
Forgetting `join` after `fork` drops work or leaks tasks
Forgetting `join` after `fork` drops work or leaks tasks