Java ForkJoinPool and CompletableFuture: Work Stealing and Composable Async Code
How ForkJoinPool's per-worker deques and work stealing keep cores busy and caches warm, and how CompletableFuture turns a request's blocking calls into a non-blocking dependency graph with timeouts and fallbacks. Plus the real costs: harder debugging, lost cancellation and a steep learning curve.
kvi5hnuCode Sprout team member9 min readOn this page
The plain thread pool from the previous article has two weaknesses: every worker competes for one shared queue, and the only way to combine results is to block in Future.get(). Java answered the first with the fork/join framework (Java 7) and the second with CompletableFuture (Java 8). Both are still everywhere, and the fork/join pool is the engine that runs virtual threads today, so it's worth understanding how they work.
ForkJoinPool: a deque per worker
A ThreadPoolExecutor has one queue that all workers take from. Under load, that single queue is a point of contention: every worker's attempt to take a task touches the same memory, and the cache line holding the queue's head bounces between cores.
A ForkJoinPool gives each worker its own double-ended queue (deque):
- When a task running on a worker creates subtasks (
fork()), they're pushed onto that worker's deque. - The worker takes its next task from the same end: newest first (LIFO). The newest subtask usually works on data the worker just touched, which is likely still in that core's cache. This is called cache affinity.
- A worker whose deque is empty doesn't sit idle. It steals a task from the other end of another worker's deque: the oldest task (FIFO).

Stealing from the opposite end has two benefits. The owner and the thief work at different ends, so they rarely contend for the same slot. And in divide-and-conquer algorithms, the oldest task is usually the biggest one, half of the whole problem, so one steal gives the thief plenty of work and the number of steals stays small. Tasks submitted from outside the pool go into separate submission queues, which workers also scan.
Using the pool directly is simple:
try (ForkJoinPool pool = new ForkJoinPool()) { // parallelism = number of cores
long words = pool.submit(() -> countWords(documents)).get();
}
Fork/join is designed for CPU-bound work that splits recursively, using RecursiveTask (returns a value) and RecursiveAction (doesn't). Parallel streams run on it too. Part 3 goes into the details: how tasks split, how join() inside a task helps instead of blocking, and why the JDK chose a ForkJoinPool as the scheduler for virtual threads.
Every JVM also has a shared common pool, ForkJoinPool.commonPool(), sized to the number of cores minus one. Parallel streams and CompletableFuture's ...Async methods use it by default. That default is important in the next section.
CompletableFuture: describe the dependencies, not the waiting
A CompletableFuture<T> is a Future that you can attach further steps to. Instead of blocking until a value is ready and then calling the next method, you say what should happen when it's ready:
| Method | Use it when the next step… |
|---|---|
thenApply(fn) | transforms the value: T → U |
thenCompose(fn) | starts another asynchronous step: T → CompletableFuture<U> |
thenCombine(other, fn) | needs this value and another future's value |
thenAccept(action) / thenRun(action) | consumes the value / just runs afterwards |
allOf(fs...) / anyOf(fs...) | waits for all / the first of several futures |
exceptionally(fn) | recovers from a failure with a replacement value |
handle(fn) | sees either the value or the exception, and returns a new value |
whenComplete(action) | observes the outcome without changing it (logging, metrics) |
orTimeout(n, unit) / completeOnTimeout(v, n, unit) | fails with TimeoutException / uses a default if not done in time (Java 9) |
Each method has an ...Async variant that runs the step on an executor instead of on whichever thread completed the previous step. Without an explicit executor, the async variants use the common fork/join pool.
The trip quote from the previous articles becomes a dependency graph. Nothing in quote blocks: it builds the graph and returns at once:
CompletableFuture<Quote> quote(long id) {
var traveler = CompletableFuture.supplyAsync(() -> loadTraveler(id), IO);
var search = CompletableFuture.runAsync(() -> recordSearch(id), IO);
var flight = traveler.thenApplyAsync(Solution::findFlight, IO);
var hotel = traveler.thenApplyAsync(Solution::findHotel, IO);
return flight.thenCombineAsync(hotel, Solution::price, IO)
.thenCombine(search, (quote, ignored) -> quote)
.completeOnTimeout(new Quote(0, "timed out, try again"), 1, TimeUnit.SECONDS)
.exceptionally(error -> new Quote(0, "unavailable: " + rootCause(error).getMessage()));
}
The graph says what depends on what: flight and hotel wait for the traveler, pricing waits for both, the result waits for the search log, and a timeout and a fallback apply to the whole thing. recordSearch now even starts in parallel with loadTraveler, since it only needs the ID.
Don't run blocking calls in the common pool. Our calls block (here in sleep, in real code on I/O). The common pool has only as many threads as cores minus one, and it's shared with every parallel stream and every other library in the JVM. A few slow blocking calls can starve all of them. That's why every async step above passes an explicit executor, IO, sized for blocking work.
Running it: success, failure and timeout
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Solution {
record Traveler(long id, String homeCity) {}
record Flight(String route, int price) {}
record Hotel(String name, int price) {}
record Quote(int total, String note) {}
static volatile boolean hotelServiceDown = false;
static volatile long airlineDelay = 100;
static Traveler loadTraveler(long id) { waitFor(100); return new Traveler(id, "Oslo"); }
static Flight findFlight(Traveler t) { waitFor(airlineDelay); return new Flight(t.homeCity() + "-Lisbon", 240); }
static Hotel findHotel(Traveler t) {
waitFor(100);
if (hotelServiceDown) throw new IllegalStateException("hotel service unavailable");
return new Hotel("Casa Azul", 360);
}
static void recordSearch(long id) { waitFor(100); }
static Quote price(Flight f, Hotel h) { waitFor(100); return new Quote(f.price() + h.price(), "priced"); }
// Blocking calls get their own pool instead of the common ForkJoinPool
static final ExecutorService IO = Executors.newFixedThreadPool(8);
static CompletableFuture<Quote> quote(long id) {
CompletableFuture<Traveler> traveler = CompletableFuture.supplyAsync(() -> loadTraveler(id), IO);
CompletableFuture<Void> search = CompletableFuture.runAsync(() -> recordSearch(id), IO);
CompletableFuture<Flight> flight = traveler.thenApplyAsync(Solution::findFlight, IO);
CompletableFuture<Hotel> hotel = traveler.thenApplyAsync(Solution::findHotel, IO);
return flight.thenCombineAsync(hotel, Solution::price, IO)
.thenCombine(search, (quote, ignored) -> quote) // finish only after the log call
.completeOnTimeout(new Quote(0, "timed out, try again"), 1, TimeUnit.SECONDS)
.exceptionally(error -> new Quote(0, "unavailable: " + rootCause(error).getMessage()));
}
public static void main(String[] args) {
long slowStart;
try (IO) {
long start = System.nanoTime();
Quote ok = quote(7).join();
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(ok + " in about " + Math.round(ms / 100.0) * 100 + " ms");
hotelServiceDown = true;
System.out.println(quote(8).join());
hotelServiceDown = false;
airlineDelay = 3_000;
slowStart = System.nanoTime();
System.out.println(quote(9).join() + " after about " + seconds(slowStart) + " s");
} // close() waits for every task, including the abandoned airline call
System.out.println("pool closed after about " + seconds(slowStart) + " s");
}
static long seconds(long since) {
return Math.round((System.nanoTime() - since) / 1e9);
}
static Throwable rootCause(Throwable t) {
return t instanceof CompletionException && t.getCause() != null ? t.getCause() : t;
}
static void waitFor(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
}
}
Output (the rounded times may differ on a busy machine):
Quote[total=600, note=priced] in about 300 ms
Quote[total=0, note=unavailable: hotel service unavailable]
Quote[total=0, note=timed out, try again] after about 1 s
pool closed after about 3 s
join() is the CompletableFuture version of get(): it waits for the result but throws the unchecked CompletionException instead of ExecutionException. Inside the pipeline, failures are also wrapped in CompletionException, which is why the fallback unwraps the cause.
The last two lines show the most important limitation. The timeout gave the caller a fallback after 1 second, but the slow airline call kept running for its full 3 seconds, holding a pool thread the whole time, and close() had to wait for it. Completing or cancelling a CompletableFuture doesn't interrupt the code computing it: cancel(true) on a CompletableFuture only marks the future as cancelled. The same goes for the failure case: when the hotel lookup failed, the flight lookup ran to completion anyway.
What CompletableFuture gives you
- Composition without blocking. Steps are chained as data dependencies, so no thread sits in
get()while waiting for the previous step. - Explicit error handling.
exceptionally,handleandwhenCompleteput recovery next to the steps they protect, and a failure skips the remaining dependent steps automatically. - Timeouts as values.
orTimeoutandcompleteOnTimeoutexpress deadlines in the pipeline itself. - Executor control. Every async step can choose where it runs.
What it costs
- A different way of thinking. The code no longer reads top to bottom. You must know which of 50-odd methods to use, when a step runs on which thread, and the difference between
thenApplyandthenApplyAsync. Mistakes are easy and often silent. - Debugging. A stack trace from inside a pipeline step shows a pool thread running a lambda, called by CompletableFuture internals. The request that started the pipeline isn't on the stack at all. Breakpoints and step-through debugging lose the thread of the story.
- Error handling is subtle. Exceptions arrive wrapped, recovery must be placed at the right point in the graph, and a future that nobody joins or observes can fail silently.
- No real cancellation. As the demo showed, abandoned work keeps running and holding resources.
- It spreads. Once a method returns
CompletableFuture, its callers must compose too, or block. Asynchronous code tends to take over a codebase.
Before adopting a heavily asynchronous style, it's worth asking whether the team can maintain it: debugging, error handling and onboarding all get harder. That question is part of why Java took a different path with virtual threads, which make simple blocking code cheap instead of asking everyone to write asynchronous code.
What's current
CompletableFuturekeeps gaining small conveniences:exceptionallyComposeandexceptionallyAsync(Java 12), andresultNow,exceptionNowandstate()(Java 19).- With virtual threads, you can pass
Executors.newVirtualThreadPerTaskExecutor()as the executor for blocking steps, so a blocked step costs almost nothing. Many teams find that, with virtual threads, plain sequential code or structured concurrency replaces mostCompletableFuturepipelines. ForkJoinPoolimplementsAutoCloseablesince Java 19, andclose()on the common pool does nothing.
Common questions
What's the difference between thenApply and thenApplyAsync?
thenApply runs the function on whichever thread completes the previous stage, or on the calling thread if that stage is already complete. thenApplyAsync always hands the function to an executor: the one you pass, or the common pool. Use the async version when the step is slow or blocking.
Why did the fallback receive a CompletionException instead of the original exception?
When a stage fails, dependent stages see the failure wrapped in a CompletionException (unless it already is one). The original exception is its cause. handle and exceptionally therefore usually unwrap it.
Is ForkJoinPool only for recursive algorithms?
It was designed for them, but it works as a general executor too, and its work stealing helps whenever tasks create more tasks. Its big role today is as the default scheduler for virtual threads.
Why not use the common pool for everything? It's small (cores − 1 threads) and shared by the whole JVM. Blocking it with I/O slows down parallel streams and every library that uses it. Give blocking work its own executor.
Summary
ForkJoinPoolgives each worker its own deque. Owners take their newest tasks (cache-warm), idle workers steal the oldest tasks from others.- Fork/join is built for CPU-bound divide-and-conquer work. The common pool runs parallel streams and default async
CompletableFuturestages. CompletableFutureexpresses a workflow as a non-blocking dependency graph withthenApply,thenCompose,thenCombine,allOf, timeouts and recovery methods.- Pass an explicit executor for blocking steps rather than using the common pool.
- Timeouts and cancellation don't stop the underlying work. Debugging, error handling and readability all get harder.
Practice questions
What does this print?
CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> 20)
.thenApply(x -> x / 0)
.thenApply(x -> x + 1)
.exceptionally(e -> -1);
System.out.println(f.join());
Answer
-1. Division by zero throws an ArithmeticException, so the second thenApply is skipped and exceptionally supplies the replacement value -1.
A service uses supplyAsync(() -> jdbcQuery()) with no executor, and under load all parallel streams in the JVM become slow. Why?
Answer
Without an executor, supplyAsync runs on the common ForkJoinPool, which has only cores − 1 threads. The blocking JDBC calls occupy those threads, so parallel streams (and anything else using the common pool) wait for a free worker. Pass a dedicated executor for blocking work.
In a fork/join pool, why does an idle worker steal the oldest task instead of the newest?
Answer
The owner works at the newest end, so stealing from the other end avoids contention. And in divide-and-conquer work, older tasks are bigger pieces of the problem, so a single steal gives the thief a lot of work. The owner keeps the small, cache-warm newest tasks.
Previous: Java Executors and Thread Pools: What They Fix and What They Don't
Next: Reactive Programming vs Virtual Threads in Java: Trade-offs and the Promise of Project Loom

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.