ForkJoinPool in Java: Work Stealing, RecursiveTask and Why Ordinary Pools Deadlock
Why divide-and-conquer with nested futures starves a fixed thread pool, and how ForkJoinPool avoids it: fork, compute and join, workers that help instead of blocking, work stealing, RecursiveTask versus RecursiveAction, thresholds, the common pool, and the CAS operations that keep it lock-free.
kvi5hnuCode Sprout team member8 min readOn this page
Article 6 introduced the ForkJoinPool's structure: a deque per worker, with owners working at one end and idle workers stealing from the other. This article looks at the problem it was built to solve, tasks that wait for their own subtasks, and at how to write such tasks correctly. That same pool, configured differently, is the scheduler for virtual threads (article 23).
The problem: tasks waiting for subtasks
Divide and conquer splits a problem in half, solves each half (often by splitting again), and combines the answers. Written with an ordinary executor, each level submits two children and calls get() on them. That works with unlimited threads. With a fixed pool, it starves: every thread ends up running a parent that is blocked waiting for children, and the children sit in the queue with no thread to run them. Nothing fails, nothing throws. The program simply stops making progress.

A fork/join worker handles waiting differently. When it calls join() on a subtask that hasn't finished, it doesn't just block. It looks for that subtask in its own deque and runs it, or runs other pending tasks, or helps whichever worker stole it. The waiting thread keeps working, so the tree of tasks always completes.
Seeing both
The program totals two million fare prices by splitting the range until pieces have 50,000 elements, first with nested futures on a fixed pool of 4, then as a RecursiveTask on a ForkJoinPool of 4:
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Solution {
static final long[] PRICES = new long[2_000_000]; // e.g. one day of fare prices to total up
static { for (int i = 0; i < PRICES.length; i++) PRICES[i] = i % 500; }
static final int THRESHOLD = 50_000;
static long sumDirect(int from, int to) {
long sum = 0;
for (int i = from; i < to; i++) sum += PRICES[i];
return sum;
}
// Divide and conquer with plain futures: each parent submits two children and blocks on them
static long sumWithFutures(ExecutorService pool, int from, int to) throws Exception {
if (to - from <= THRESHOLD) return sumDirect(from, to);
int mid = (from + to) >>> 1;
Future<Long> left = pool.submit(() -> sumWithFutures(pool, from, mid));
Future<Long> right = pool.submit(() -> sumWithFutures(pool, mid, to));
return left.get() + right.get(); // a pool thread waits, doing nothing
}
// The same with fork/join: fork one half, compute the other, then join
static final Set<String> workers = ConcurrentHashMap.newKeySet();
static class PriceSum extends RecursiveTask<Long> {
private static final long serialVersionUID = 1L;
private final int from, to;
PriceSum(int from, int to) { this.from = from; this.to = to; }
@Override protected Long compute() {
workers.add(Thread.currentThread().getName());
if (to - from <= THRESHOLD) return sumDirect(from, to);
int mid = (from + to) >>> 1;
PriceSum left = new PriceSum(from, mid);
left.fork(); // push onto this worker's deque
long right = new PriceSum(mid, to).compute(); // work on the other half ourselves
return right + left.join(); // join runs or helps with pending tasks
}
}
public static void main(String[] args) throws Exception {
System.out.println("expected total: " + sumDirect(0, PRICES.length));
ExecutorService fixed = Executors.newFixedThreadPool(4);
Future<Long> total = fixed.submit(() -> sumWithFutures(fixed, 0, PRICES.length));
try {
System.out.println("fixed pool of 4: " + total.get(2, TimeUnit.SECONDS));
} catch (TimeoutException e) {
System.out.println("fixed pool of 4: no result after 2 s, all 4 threads are parents waiting for children");
}
fixed.shutdownNow();
try (ForkJoinPool forkJoin = new ForkJoinPool(4)) {
long result = forkJoin.invoke(new PriceSum(0, PRICES.length));
System.out.println("ForkJoinPool(4): " + result + ", used more than one worker: " + (workers.size() > 1)
+ ", tasks stolen: " + (forkJoin.getStealCount() > 0 ? "some" : "none"));
}
}
}
Output:
expected total: 499000000
fixed pool of 4: no result after 2 s, all 4 threads are parents waiting for children
ForkJoinPool(4): 499000000, used more than one worker: true, tasks stolen: some
The fixed pool never produced an answer. The first four tasks it ran were all parents, and they're still waiting. The program needs shutdownNow() to interrupt them, or it would hang forever. The fork/join version returned the correct total, with several workers sharing the work by stealing.
The fixed-pool version would have "worked" with enough threads, but the number needed grows with the depth of the tree, and each blocked platform thread is wasted memory. With virtual threads it would complete (each blocked parent costs only a little heap), which is part of why structured concurrency (Part 4) can use simple blocking joins. For CPU-bound splitting, though, fork/join is the right tool: it keeps exactly one thread per core busy.
The fork, compute, join idiom
Fork/join tasks extend one of three classes:
| Class | Use for |
|---|---|
RecursiveTask<V> | tasks that return a value (compute() returns V) |
RecursiveAction | tasks that return nothing, such as sorting an array in place |
CountedCompleter<T> | advanced: completion triggered by pending-count, without blocking joins. The JDK's parallel streams use it |
Inside compute(), the pattern is:
if (small enough) return solveDirectly();
Task left = new Task(firstHalf);
left.fork(); // 1. make the left half available to other workers
long right = new Task(secondHalf).compute(); // 2. do the right half on this thread
return right + left.join(); // 3. then collect the left half
The order matters:
- Fork one, compute the other. Forking both halves and then joining both leaves the current thread idle while it waits. Computing one half directly uses the thread you already have.
- Join last.
left.fork(); left.join(); right.compute()makes the work sequential: the thread waits for the left half before even starting the right. - Join in reverse order of forking when forking several subtasks. Recently forked tasks are on top of your own deque, so joining them first usually means running them yourself, which is cheapest.
invokeAll(t1, t2)is a convenient shortcut that forks and joins a group of tasks in the right way.
Choosing the threshold
Each task has overhead: an object, a deque push, possibly a steal. Splitting down to single elements spends more time on overhead than on work. Not splitting enough leaves cores idle. A rough guide is to aim for leaf tasks that take somewhere between 10 and 100 microseconds of work, or about 4 to 16 times as many leaf tasks as cores. Measure with JMH for real decisions. In practice, if you just need to process a collection in parallel, a parallel stream already does this splitting for you, on the common pool.
The common pool
ForkJoinPool.commonPool() is a shared, JVM-wide fork/join pool. Parallel streams, CompletableFuture.supplyAsync without an executor, and Arrays.parallelSort use it. Its parallelism defaults to the number of cores minus one, because the thread that starts the work usually takes part too. It can be configured with -Djava.util.concurrent.ForkJoinPool.common.parallelism=N.
Because it's shared, never block in the common pool with I/O or long sleeps. A few blocked tasks can stall every parallel stream in the application. Blocking work belongs on its own executor or, better, on virtual threads. When blocking inside a fork/join pool is unavoidable, ForkJoinPool.managedBlock tells the pool to add a compensating thread. The virtual-thread scheduler uses a version of this trick (article 23).
Virtual threads don't run on the common pool. The scheduler is a separate ForkJoinPool, so parallel streams and virtual threads don't compete for the same workers.
CAS: how the pool avoids locks
A work-stealing deque is touched by its owner at one end and by thieves at the other, often at the same instant. Locking it on every push and pop would cost far more than the tasks themselves. Instead, ForkJoinPool uses compare-and-set (CAS): a single CPU instruction that updates a value only if it still holds the value you expect, and reports whether it succeeded. If another thread got there first, you re-read and retry.
You can use the same operation through the java.util.concurrent.atomic classes, or directly through a VarHandle:
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
/** Counts booked seats without a lock, using compare-and-set in a retry loop. */
public class SeatCounter {
private volatile int booked;
private final int capacity;
private static final VarHandle BOOKED;
static {
try {
BOOKED = MethodHandles.lookup().findVarHandle(SeatCounter.class, "booked", int.class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
public SeatCounter(int capacity) { this.capacity = capacity; }
/** Books one seat if any is left. Never overbooks, even with many threads. */
public boolean tryBook() {
while (true) {
int current = booked; // read the current value
if (current >= capacity) return false; // sold out
if (BOOKED.compareAndSet(this, current, current + 1)) return true; // won the race
// another thread changed 'booked' between our read and our CAS: retry
}
}
public int booked() { return booked; }
}
AtomicInteger.compareAndSet and updateAndGet do the same thing with less ceremony and are the better choice in application code. VarHandle is for library code that needs CAS on a plain field without a wrapper object, which is exactly what ForkJoinPool does internally.
What's current
ForkJoinPoolimplementsAutoCloseablesince Java 19, so pools you create work in try-with-resources. Closing the common pool does nothing.- Java 25's
ForkJoinPoolalso implementsScheduledExecutorService, with delayed and periodic tasks handled by an internal delay scheduler. That's thedelaySchedulerthread that shows up in thread dumps. - Parallel streams and
Arrays.parallelSortstill run on the common pool. Virtual threads run on their ownForkJoinPool.
Common questions
Is ForkJoinPool only for recursive tasks?
No. It's a general ExecutorService, and its per-worker deques reduce contention for any workload where tasks create more tasks. It shines for CPU-bound divide and conquer, and it's used in asyncMode (FIFO) as the virtual-thread scheduler.
Why did the fixed pool hang instead of throwing?
Every thread was legitimately waiting in get(). There's no deadlock detector for this situation, called thread-starvation deadlock: from the JVM's point of view, the threads are simply waiting. Thread dumps show it: all pool threads parked in FutureTask.get.
Can I call blocking I/O inside a RecursiveTask?
You can, but each blocked task holds a worker, and the pool's parallelism is usually the number of cores. Do I/O elsewhere, or wrap it in ForkJoinPool.managedBlock.
Should compute() catch exceptions?
Usually not. An exception thrown in a subtask is rethrown by join() (as an unchecked exception) or by invoke(), so it reaches the caller of the top-level task.
Summary
- Divide and conquer with nested
Future.get()calls starves a fixed pool: all threads become waiting parents, and the children never run. - In a
ForkJoinPool,join()helps: the waiting worker runs the subtask itself or other pending tasks, so the tree always completes. - Fork one half, compute the other on the current thread, then join. Join recently forked tasks first.
- Pick a threshold that makes leaf tasks big enough to outweigh task overhead, or use parallel streams.
- The shared common pool must not be blocked. Virtual threads use a separate pool.
- Work-stealing deques rely on CAS instead of locks. In your own code, use the atomic classes for the same effect.
Practice questions
What's wrong with this compute() method?
protected Long compute() {
if (to - from <= THRESHOLD) return sumDirect(from, to);
int mid = (from + to) >>> 1;
PriceSum left = new PriceSum(from, mid);
PriceSum right = new PriceSum(mid, to);
left.fork();
long l = left.join();
long r = right.compute();
return l + r;
}
Answer
It joins the left half immediately after forking it, before working on the right half, so the two halves never run in parallel on this path. It works, but sequentially. Compute the right half first, then join the left: long r = right.compute(); return r + left.join();.
Why is it a bad idea to run JDBC queries inside a parallel stream?
Answer
Parallel streams run on the common ForkJoinPool, which has about one thread per core and is shared by the whole JVM. Blocking queries hold those few workers, so the stream gains little concurrency and every other parallel stream and default CompletableFuture stalls meanwhile. Run blocking calls on virtual threads (with a connection pool as the limit) instead.
In SeatCounter.tryBook, why is the capacity check inside the loop instead of before it?
Answer
Other threads may book seats between iterations. After a failed CAS, booked has changed, possibly reaching the capacity. Re-checking inside the loop, against the value just read, ensures the counter never goes past the capacity.
Previous: Callable and Future in Java: Task Results, Timeouts, Cancellation and invokeAll
Next: The Virtual Thread Scheduler: How ForkJoinPool Runs Java Virtual Threads

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.