On which thread does a CompletableFuture exception-handling callback run, and what subtle bugs arise from that plus from where you place handle/whenComplete in the chain?
answer
- Non-async: usually the completing thread, often commonPool
- Blocking in a callback can starve the shared common pool -> use *Async with a bounded executor
- Handler only catches failures from stages ABOVE it -> put it last
- whenComplete logs but does not recover
- Unwrap CompletionException before instanceof; observe the terminal stage
basics
~20 sA non-async callback usually runs on whichever thread completed the stage (often a shared pool thread), so heavy or blocking work there can starve the pool. Where you put handle/whenComplete also matters: it only sees failures from stages above it, not below.
solid answer
~50 sNon-async callbacks (exceptionally, handle, whenComplete) usually run on the thread that completed the upstream stage — or the caller's thread if it was already complete; the Javadoc allows any caller of a completion method. For supplyAsync that's typically a ForkJoinPool.commonPool worker, which is shared process-wide; doing blocking I/O or heavy CPU work in a callback can starve that pool and stall unrelated tasks. The *Async overloads (handleAsync, exceptionallyAsync, whenCompleteAsync) let you hand the callback to a dedicated executor to avoid this. Placement is the second trap: an error handler only catches failures from stages *above* it; a thenApply added *after* exceptionally can still throw and bypass it. So put handle/exceptionally at the end (or re-handle). A third trap: whenComplete logs but doesn't recover, so people add it expecting recovery and the failure silently propagates. And forgetting to unwrap CompletionException makes instanceof checks miss the real cause.
code
java · 16 linesExecutorService io = Executors.newFixedThreadPool(16);
// GOOD: blocking recovery on a dedicated bounded executor, handler at the tail
fetchAsync(id)
.thenApply(this::transform)
.handleAsync((value, ex) -> { // runs on `io`, not the common pool
if (ex != null) {
Throwable cause = (ex instanceof CompletionException)
? ex.getCause() : ex;
return loadFromBackup(id); // blocking call, isolated
}
return value;
}, io)
.whenComplete((v, ex) -> { // terminal observation: never lose a failure
if (ex != null) log.error("chain failed", ex);
});go deeper
May assume callbacks always run on a background thread and that any error handler catches everything; unaware of pool/placement issues.
Knows *Async picks an executor and that whenComplete doesn't recover; may miss the common-pool starvation and placement-order traps.
Explains completing-thread vs caller-thread execution, common-pool blocking risk, handler-placement scoping, and the unwrap requirement.
Sets codebase-wide conventions: dedicated bounded executors, terminal failure observation, non-blocking timeouts, standardized unwrapping, and reviews chains for placement and blocking anti-patterns.
## Which thread runs the callback? The `CompletableFuture` Javadoc says actions passed to **non-async** methods "may be performed by the thread that completes the current CompletableFuture, or by any other caller of a completion method." Two cases dominate: 1. **The thread that completed the upstream stage** — if the stage is still pending when you attach the callback, whoever eventually completes it usually runs your callback. For `supplyAsync(...)` without an explicit executor, that's a worker of **`ForkJoinPool.commonPool()`** (a single JVM-wide pool, sized to roughly `CPU - 1`). Since JDK 25 that holds on every machine; before 25, a common pool configured with parallelism below 2 made each async task run on a new thread instead. 2. **The calling thread** — if the upstream stage is **already complete** when you attach the callback, the callback may run *inline* on the thread attaching it. Neither case is a promise, and this non-determinism is the root of several subtle bugs. ### Pitfall 1 — pool starvation / blocking on the common pool Because non-async callbacks often run on the **shared** common pool, doing **blocking I/O** (a DB call, `join()` on another future, a network request) or **heavy CPU** work inside `handle`/`exceptionally`/`whenComplete` ties up a pool worker. The common pool is small and shared: parallel streams use it by default, and so does every `*Async` method called without an executor, so one team's blocking callback can stall unrelated workloads. **Fix:** use the `*Async(fn, myExecutor)` overloads with a **dedicated, bounded executor** for anything blocking, keeping the common pool for short non-blocking transforms. ### Pitfall 2 — handler placement (it only catches what's above it) Error handlers are *stages*; they only observe failures from stages **earlier** in the chain. This is wrong: ```java cf.exceptionally(ex -> fallback()) // catches failures from cf .thenApply(this::risky); // if THIS throws, it is NOT caught above ``` If `risky` throws, the chain ends exceptionally with no handler. Put the handler **last**, or add another after the risky stage. Conversely, placing `handle` early then chaining more transforms means later failures escape it. ### Pitfall 3 — whenComplete doesn't recover Developers add `whenComplete((v, ex) -> log(ex))` expecting it to *swallow* the error. It doesn't: the original failure **passes through** (as a `CompletionException` if it was not one already). Recovery requires `exceptionally`/`handle`. Misusing `whenComplete` leads to "I logged it, why is the chain still failing?" Also: if the `whenComplete` action throws *after an upstream success*, that new exception replaces the result — an accidental failure injection. ### Pitfall 4 — forgetting to unwrap CompletionException In a downstream handler the throwable is wrapped in `CompletionException`. An `instanceof MyDomainException` check then **fails** because you actually hold a `CompletionException`. Always normalize via `getCause()` before type checks. ### Pitfall 5 — exceptions thrown while *assembling* the chain If the **supplier/function reference itself** is null or you throw while *building* the pipeline (outside a stage), that's a plain synchronous exception on the assembling thread, not a future failure — different handling path. ### Pitfall 6 — swallowing failures by never blocking/observing If you build a chain ending in `exceptionally`/`handle` but never `join()`/`get()` it and never log inside, an early failure can be **silently lost** because nothing observes the terminal stage. Fire-and-forget futures should always have a terminal `whenComplete`/`exceptionally` that logs. ## Design guidance (principal lens) - **Default to `*Async` with an explicit, bounded executor** for any callback that might block; never block the common pool. - **Standardize a single unwrap helper** so every handler sees the real cause. - **Make the terminal stage observe failures** (log/metric) — async errors that nobody reads are operational blind spots. - **Document handler placement conventions**: error handling belongs at the *tail* (or is re-applied after each risky stage). - **Prefer non-blocking timeouts** (`orTimeout`, `completeOnTimeout`) over blocking `get(timeout)` so you don't tie up threads. ## Mental model A `CompletableFuture` chain is a relay: the *baton* (value or failure) is handed thread-to-thread. You don't control which runner carries it unless you say `*Async(..., executor)`. And a `catch` (`exceptionally`/`handle`) only guards the part of the track *before* it — anything dropped *after* keeps falling.
- Why is calling join() inside a CompletableFuture callback dangerous?The callback may run on a common-pool worker; blocking it with join() removes a thread from a small shared pool and can cause starvation or deadlock if the awaited future needs the same pool. Use composition (thenCompose/exceptionallyCompose) instead of blocking.
- How do you ensure a fire-and-forget future's failures aren't lost?Attach a terminal whenComplete/exceptionally that logs or records a metric on the throwable, so an unobserved exceptional completion still surfaces operationally.
- If you add thenApply after exceptionally and that thenApply throws, what handles it?Nothing in that chain — exceptionally only catches failures upstream of itself. You need another error handler after the risky stage, or move the handler to the tail.
- Doing blocking I/O or join() inside a non-async callback on the common pool
- Putting exceptionally/handle in the middle and chaining risky transforms after it
- Using whenComplete and expecting it to suppress/recover the failure
- Fire-and-forget chains with no terminal failure observation (silent loss)
- instanceof checks without unwrapping CompletionException
- Async methods always use the common pool
- Java 25
- CompletableFuture.exceptionallyAsync
- Java 12
Assumes JDK 27. Since JDK 25, CompletableFuture's async methods without an explicit executor always run in the ForkJoinPool common pool; before 25, a common pool with parallelism below 2 got a new thread per async task, so on a one- or two-CPU host the completing thread differed. JDK 25 and 27 agree.
context
- CompletableFuture (Java SE 27 & JDK 27)docs.oracle.com
- ForkJoinPool (Java SE 27 & JDK 27)docs.oracle.com