Lesson · Executors, Thread Pools & Async Programming
ForkJoinPool: divide, steal, join
15 min readForkJoinPool & Recursive Tasks
Divide and conquer is easy to write and hard to schedule: the recursion knows the shape of the work, and something has to hand those tasks to a fixed set of threads without a central queue. ForkJoinPool does it with a deque per worker, LIFO for the owner and FIFO for thieves.
A loop that becomes a tree
Summing a large array, walking a tree, merge sort: the same shape every time. The answer for the whole problem follows from the answers for two halves, so the work can be described as a tree of tasks that keep splitting until the pieces are small enough to solve with a plain loop.
Fork/join is that shape written down. A RecursiveTask<V> has a compute() that returns a value; a RecursiveAction has one that returns nothing. Above a threshold a task splits into smaller tasks, below it the task solves its slice with ordinary sequential code.
The framework owns the scheduling: it decides which worker runs which task. You own the recursion and the threshold, which is the only tuning knob that matters.
- RecursiveTask<V>: compute() returns V, collected by join() or invoke(). Sums, counts, maximums, sorted results.
- RecursiveAction: compute() returns void, used for in-place work such as a parallel sort step or applying an operation across a structure.
- ForkJoinPool: the executor those tasks run on. Its parallelism (the number of worker threads) is a separate decision from the shape of the tree.
You write the tree; the pool decides who runs it. Task count and thread count are independent numbers, and that independence is the whole design.
compute(): split, fork one half, solve the other
The shape of compute() is three moves: check the threshold, split, then fork one half, compute the other half, join the forked one and combine.
fork() hands the task to the pool. On a worker thread it is pushed onto that worker's own deque, where any idle worker can steal it. join() waits for the result, and if the task was never taken it may be run by the joining thread itself rather than parking it: a join can do real work, which is one of the reasons the framework is not just an executor with a tree API.
Fork one half and compute the other is the standard pattern because it keeps the current thread busy. Forking both halves and joining them does the same amount of arithmetic, but the forking worker spends the time waiting, which is exactly what work stealing is trying to avoid.
@Override protected Long compute() { if (hi - lo <= THRESHOLD) { // base case: a plain loop, no new tasks long sum = 0; for (int i = lo; i < hi; i++) { sum += data[i]; } return sum; } int mid = (lo + hi) >>> 1; // unsigned shift: no midpoint overflow ParallelSum left = new ParallelSum(data, lo, mid); ParallelSum right = new ParallelSum(data, mid, hi); right.fork(); // pushed onto this worker's deque, stealable long leftSum = left.compute(); // this thread keeps working long rightSum = right.join(); // waits for the other half, or runs it if nobody stole it return leftSum + rightSum; // values combine on the way back up the tree }
Fork one half, compute the other. The forked half is bait for idle workers; the computed half is what keeps the current worker off the join.
The pool and its deques
Every worker thread in a ForkJoinPool owns a deque of tasks. fork() pushes the new task onto the calling worker's own end of its deque, and when that worker needs its next task it pops from the same end: last in, first out, so the newest task is also the one whose data is still hot in cache.
When a worker's deque runs dry it does not sit idle, and there is no central queue handing out work. It goes to another worker's deque and steals from the opposite end: the oldest task, forked first, which is almost always the largest chunk still outstanding. One steal buys a lot of work, the victim gives up only its coldest task, and every operation touches one of the two ends of a deque, which is what makes the structure cheap under contention.
Own the hottest end, steal from the coldest. LIFO for the worker that created the tasks, FIFO for the thieves: cache locality on one side, load balancing on the other.
fork/join · one tree, two ends per deque
fork one half, compute the other, join what comes back
the task tree · 12 elements, threshold 3
Every internal node waits at a join for its two children and adds their values. The tree may hold thousands of tasks; the pool still has one thread per unit of parallelism.
the two deques · where these tasks actually wait
A steal takes the oldest task, forked first and usually the biggest remaining chunk, so one steal keeps the thief busy and leaves the owner alone at the end its cache already knows.
commonPool parallelism defaults to availableProcessors() - 1 and is shared with parallel streams. A worker parked in a plain blocking call cannot steal; ManagedBlocker is the protocol that asks the pool to compensate with a spare thread.
One split, one steal, one combine
The player below replays a small run: twelve numbers, a threshold of three, two workers. Worker 1 forks the right half and starts on the left one, and then the idle worker does what the design expects it to do.
Watch the two deques rather than the arithmetic. The interesting event is the steal, and the interesting question is which end of the deque it comes from.
A steal is not an emergency, it is the plan. The pool assumes workers finish unevenly; the deque is where that assumption is implemented.
fork/join · work stealing in motion
picking up the root task
nothing to do yet
values combined so far
main submits sum[0,12): twelve numbers, threshold 3. The common pool sizes itself from the host, and only two of its workers appear in this trace.
Blocking inside a worker
A worker parked in a blocking call cannot steal. It holds a thread, contributes nothing, and its deque stays full; with enough blocked tasks a pool of eight behaves like a pool of two. The pool does not grow to compensate for blocks it cannot see.
For blocking that genuinely cannot be avoided, the framework defines a protocol. Implement ManagedBlocker with isReleasable() and block(), and call ForkJoinPool.managedBlock(blocker): while the blocker runs, the pool may add a spare thread so that parallelism does not collapse. That is the compensation it refuses to offer for an unsignalled block.
Better than either option: keep waiting out of fork/join tasks altogether. A fork/join pool is for CPU-bound work, and the waiting shapes live in the executor and future lessons.
commonPool is not yours: do not block in it. It is shared with every parallel stream in the process, so a blocking task there slows down code you have never seen.
commonPool, or a pool of your own
fork() uses the pool it is called from. Called outside any pool, tasks land in ForkJoinPool.commonPool(), whose parallelism defaults to availableProcessors() - 1 and can be overridden with the system property java.util.concurrent.ForkJoinPool.common.parallelism. Parallel streams run on that same pool.
A custom pool is one constructor away: new ForkJoinPool(parallelism), then invoke() or submit() to enter it. It costs one more object, and it buys isolation: a subsystem with its own pool cannot be starved by another subsystem's tasks, and a slow pool cannot be blamed on the common one.
| ForkJoinPool.commonPool() | new ForkJoinPool(n) | |
|---|---|---|
| Who uses it | every fork/join task and parallel stream that does not name a pool | only the code you submit to it |
| Parallelism | availableProcessors() - 1 by default, one value for the JVM | whatever you pass to the constructor |
| Isolation | none: your tasks compete with every other stream in the process | complete: another subsystem cannot starve your work |
| Reach for it when | simple CPU-bound work that never blocks | you need a different size, a separate failure domain, or blocking that must be contained |
Tune parallelism, not thread counts. You choose how many workers exist; the tree decides how much work there is to hand them.
The ways a fork/join program goes wrong
The failure modes are few and they repeat: shared state, thresholds, mistaking tasks for threads, and joining at the wrong moment.
- Shared mutable state in tasks. Any worker may run any task, so results must travel up the tree as return values. A mutable field in a recursive task is a race with a friendly name.
- A threshold that is too small. Every split allocates a task and touches a deque; if a leaf is a handful of additions, the framework costs more than the work. Too large is the other failure: nothing to steal, so one worker does everything. Measure per element, then pick.
- Confusing tasks with threads. A tree with hundreds of thousands of nodes runs on the same handful of workers. Task objects must be cheap, and no task may depend on another task running at the same time in order to make progress.
- fork then join with nothing in between. The forked half may still be stolen, but if nobody is idle it just runs on the calling thread, and you have paid task overhead for a local call. Either interleave real work between the two, or do not fork at all.
- Exceptions that vanish. An exception thrown by compute() is recorded in the task and rethrown by join() or get(). A fire-and-forget task that nobody joins has nobody to rethrow to, so its failure never surfaces anywhere.
Return values are the communication channel. A recursive task that writes into a shared field has moved its race one level up the tree.
When fork/join fits, and when it does not
Fork/join fits CPU-bound work that splits cleanly: recursive structures, big arrays, divide-and-conquer over memory. It does not fit waiting. Every blocked worker is a worker that cannot steal, which removes the mechanism the pool runs on.
- Fits: large in-memory data, arithmetic over independent chunks, recursion whose halves do not talk to each other, per-element work heavy enough to dwarf the task overhead.
- Does not fit: I/O, database calls, locks, sleeps, or anything whose progress depends on another task finishing first.
- Alternatives: parallel streams for simple data-parallel pipelines over collections, run on the common pool; executors with futures for independent tasks that block; a plain loop whenever the data is small enough that splitting costs more than it saves.
Fork/join is for CPU-bound trees, not for waiting. The moment a task blocks, the mechanism that makes the pool fast stops working.
Blocking in a worker does not create a thread, it removes one
The pool's size is its parallelism, and nothing inside a task changes that: a worker parked in a blocking call cannot steal and cannot be replaced. On the common pool the damage is process-wide, because every parallel stream queues behind the same workers. ManagedBlocker exists for the rare unavoidable case, since it tells the pool to compensate with a spare thread while the block runs. If most of your tasks wait, the right tool is an executor or virtual threads, not a fork/join pool.
Interview angles
What does ForkJoinPool solve that a thread pool does not?+
A thread pool runs tasks that arrive from outside; fork/join runs a tree of tasks that your own code creates recursively. Work stealing keeps every worker busy without a central queue, which is what makes divide-and-conquer parallelism practical.
The two are still executors underneath, and ForkJoinPool is also a plain ExecutorService. The specialisation is the deque-per-worker scheduling policy.
How does work stealing work?+
Each worker owns a deque. New forked tasks are pushed at the worker's own end and popped back from that same end, LIFO, keeping the newest and hottest data nearby. When a worker runs dry it steals from the opposite end of another worker's deque.
Because pushes, pops and steals all happen at the two ends of a deque, one worker never has to lock the middle of another worker's queue, and the structure stays cheap under contention.
Why steal the oldest task rather than the newest?+
The oldest task was forked first, so it is typically the biggest chunk of work left: a single steal keeps the thief busy. It also leaves the victim's newest tasks alone, which keeps its cache warm and collisions rare.
What is ManagedBlocker for?+
It is how a worker tells the pool that it is about to block in something the pool cannot see. While the blocker runs, the pool can compensate by starting a spare thread, so effective parallelism does not drop.
Without the protocol, a blocking call just parks a worker: the pool does not know the worker is idle, so it does not replace it, and stealing collapses.
Common misconception: The pool detects any blocked worker and adds a thread automatically.
What goes wrong when the threshold is set badly?+
Too small and the per-task overhead of allocating, forking and joining outweighs the work; too large and the tree has no pieces worth stealing, so one worker does everything. The right value comes from measuring per-element cost.
The optimum is machine-dependent and data-dependent, so the threshold is a tuning parameter with a measured default, not a rule of thumb.
What is the default parallelism of the common pool, and who else uses it?+
It defaults to availableProcessors() - 1, and the system property java.util.concurrent.ForkJoinPool.common.parallelism can override it. Parallel streams use the same pool, so blocking work submitted there slows every stream in the process.
Common misconception: The common pool is a scratch pool that only your code touches.