Lesson · Executors, Thread Pools & Async Programming
CompletableFuture: stage composition and failure paths
17 min readCompletableFuture
CompletableFuture is the push half of the Future contract: you describe stages, each stage runs when its input exists, and no thread parks on the answer. The same graph carries failures, so recovery, timeouts and the question of which thread runs a callback are all part of one model.
From claim ticket to assembly line
A Future answers one question well, which is whether there is a value and what it is. It refuses the next three: it cannot tell you when the value arrives, it cannot be combined with another future, and it cannot recover from its own failure. Each of those needs another thread parked on get().
CompletableFuture implements Future and adds CompletionStage, a description of what happens after a stage completes. supplyAsync starts one, every following call adds the next, and the chain runs as inputs arrive while the caller is free.
One warning before the API. A chain is eager, not lazy: attaching a stage subscribes it, so the pipeline runs whether or not the final result is ever read, and a failure is stored even when no reader exists. The HTTP client lesson used sendAsync; this lesson is the general form of the machinery behind it.
CompletableFuture<String> name = CompletableFuture .supplyAsync(() -> fetchUser(userId), ioPool) // starts immediately, on the I/O pool .thenApply(User::displayName) // runs on the thread that completed the fetch .exceptionally(e -> "anonymous"); // the chain still has a value if it fails String printed = name.join(); // only the edge of the program waits
A Future is a value you ask for; a CompletableFuture is a chain you describe and then read once.
The stage vocabulary: map, flatten, join, consume
Almost every stage method is one of four shapes: transform a value, replace a value with another future, combine two futures, or consume a value and end the chain. The names follow the shapes, and everything else is a convenience around them.
CompletableFuture<CompletableFuture<Invoice>> nested = CompletableFuture.supplyAsync(this::loadOrder).thenApply(this::invoiceFor); // wrong shape CompletableFuture<Invoice> flat = CompletableFuture.supplyAsync(this::loadOrder).thenCompose(this::invoiceFor); // flattened
| Stage | Shape | What it does |
|---|---|---|
| thenApply(fn) | map | transforms the value; the next stage sees a plain value |
| thenCompose(fn) | flatMap | calls a function that itself returns a future, and flattens it, so the chain stays one level deep instead of CompletableFuture<CompletableFuture<T>> |
| thenCombine(other, fn) | zip | waits for this stage and one independent future, then combines both values into one |
| thenAccept(fn) / thenRun(fn) | consume | terminal: accept takes the value, run ignores it, both return CompletableFuture<Void> |
| allOf / anyOf | aggregate | allOf waits for every future and yields Void; anyOf completes with the first outcome, typed as Object |
| exceptionally / handle / whenComplete | failure | recover, recover-and-inspect, or observe; the failure section has the differences |
- thenCompose flattens, thenCombine joins: neither steals a thread. thenCompose is for a stage that starts more work; thenCombine is for two pieces of work that were independent from the beginning.
- allOf waits for everything, then reports. It completes only when every input is done, and if one failed it completes exceptionally with that failure as the cause. The other outcomes stay in their own futures, so gather them there instead of relying on the one exception allOf kept.
- anyOf returns the first outcome, a failure included, typed as Object. If you want the first success, build it from handle fallbacks. Also note the asymmetry: an empty allOf is already complete, while an empty anyOf never completes at all.
- A non-blocking read exists on this class, not on Future. getNow(fallback) returns the value when it is already there and the fallback otherwise.
- Checked exceptions need one wrap. Supplier.get and Function.apply declare nothing, so a call that throws IOException goes inside a try/catch that rethrows as CompletionException, which keeps the cause intact and is the shape a chain expects.
A stage is a description of what to do when a value exists, not a place where a thread waits.
CompletableFuture · one graph, two rails
values travel the normal rail; a failure takes the same route and skips what needs a valuethe normal rail
Starts the pipeline. The future exists immediately and the pool thread does the waiting.
A plain stage: it runs on the thread that completed the fetch, so the hop costs no thread.
Joins two independent futures. The stage runs when both inputs have values, on whichever one finished last.
Terminal: consumes the value, returns CompletableFuture<Void>, and is what a reader awaits.
the independent input
Started at the same time as the user fetch. It is not a stage of the first chain: it is a second future that thenCombine waits for.
the two shapes
thenCompose is for a stage that starts more work and would otherwise nest a future inside a future. thenCombine is for work that was independent from the beginning.
Nothing on this rail is thrown at a thread: the failure is stored in the first stage that failed and copied into every dependent stage, so whenComplete can observe it and pass it on while handle replaces it with a value. If no handler ever absorbs it, the failure is still there at the edge, which is why a chain nobody reads is a failure nobody sees.
Which thread runs a callback
Every stage method with an Async suffix names an execution venue explicitly: the executor you pass, or ForkJoinPool.commonPool() when you pass nothing. The plain forms name nothing, so they run on the thread that completes the upstream stage, or on any caller that completes it, including you when the value was already there.
That rule has two consequences worth planning for. A plain chain adds no threads and no scheduling, so an I/O completion can continue straight into a cheap transform, which is the cheapest hop available. An Async hop is how work moves deliberately: off an I/O thread before a CPU-heavy step, or onto a bounded executor before anything that blocks.
| Form | Runs on |
|---|---|
| thenApply, thenCompose, thenCombine, thenAccept | the thread that completes the upstream stage, or the caller that completes it |
| ...Async(fn) | ForkJoinPool.commonPool() |
| ...Async(fn, executor) | the executor you supplied |
- Never block inside a commonPool task. The common pool has parallelism of available processors minus one and is shared with parallel streams, so one blocked task there stalls unrelated work.
- Choose the venue per stage, not per chain. A cheap transform on the completing thread next to an expensive one on a bounded CPU pool is normal and deliberate.
- Completing on the caller is a feature. Attaching a stage to an already completed future runs it on the attaching thread, which keeps a chain inside a request on that request's thread.
The suffix decides the thread: Async names a venue, plain inherits the completer.
Joining independent work without a thread per wait
The composition methods exist for one situation: work that is independent and whose results are needed together. Two services in one response, a cache read next to a database read, three shards of one query. Each task has its own future, and the method you pick says how the values meet.
- Start both sources:
supplyAsync(fetchUser, ioPool)andsupplyAsync(fetchPrefs, ioPool). Two futures exist immediately and neither call blocks the caller. - Transform one source:
userFuture.thenApply(User::displayName). That stage runs on whichever thread completes the user fetch, so it adds no thread of its own. - Join the two:
nameFuture.thenCombine(prefsFuture, Page::new). The stage runs when the later of its two inputs completes, it needs no third thread, and both inputs have to succeed. - Consume:
.thenAccept(this::render)ends the chain with a side effect and returnsCompletableFuture<Void>;.join()at the edge of the request turns the graph back into a value. - For N of the same kind,
allOf(futures.toArray(CompletableFuture[]::new)).join()waits for every one of them, then read each future's own result, because allOf collapses the failures into a single exception.
Combination is not concurrency: the futures were already running; thenCombine only says where the values meet.
A failure is a value in the same chain
An exception in a stage is stored in that stage's future, and every dependent stage that needs the value is skipped rather than executed: the next future completes exceptionally with the same failure, usually wrapped in a CompletionException. Nothing is retried, no thread is unwound, and no uncaught exception handler runs. The failure is a value travelling down the same chain.
Three methods handle that value, and they differ in one thing: whether the failure survives. exceptionally(fn) runs only on failure and replaces it with a value. handle(fn) always runs and can replace either outcome. whenComplete(fn) observes and passes the same outcome on, so a failure keeps travelling until something absorbs it.
CompletableFuture<String> name = fetchUser(userId) .thenApply(User::displayName) // throws when the record is incomplete .exceptionally(e -> "anonymous") // recover: downstream sees an ordinary value .thenCombine(fetchPrefs(userId), Page::new) // the chain continues as if nothing happened .whenComplete((page, e) -> metrics.record(page, e)); // observe only: the outcome passes through
- exceptionally recovers and does nothing else. It is a catch block: the function is not called when the stage succeeded, and its returned value becomes the chain's value.
- handle is the general answer. It receives the value and the exception, one of which is null, and it decides the next value, which makes it the natural place to turn a failure into an error message or a fallback.
- whenComplete does not absorb. It exists for logging and metrics; the outcome continues unchanged, and an action that throws replaces the outcome only when the upstream had not already failed.
- Unwrap where you handle. A propagated failure arrives as a CompletionException whose cause is the original throwable, and
join()rethrows exactly that; check the type before switching on it. - Cancellation propagates the same way. Cancel an upstream stage and its dependents complete with CancellationException, because they were waiting for a value that will never exist.
A failure propagates down the same chain as a value; handle is where it stops being one.
CompletableFuture · fetch → transform → combine → render
started on ioPool
started on ioPool
waiting for an input
waiting for an input
waiting for an input
Two independent sources start at once: supplyAsync(fetchUser, ioPool) and supplyAsync(fetchPrefs, ioPool). Each call returns a future immediately, both tasks are already travelling on the I/O pool, and the caller holds two tickets without parking.
Timeouts: orTimeout and completeOnTimeout
Java 9 added two methods to this class, and both complete the future rather than cancelling the work. orTimeout(2, SECONDS) completes it exceptionally with a TimeoutException if it is still pending, and completeOnTimeout(fallback, 2, SECONDS) completes it with the fallback value instead.
Both are honest about what a timeout is: a rule for whoever reads the value. The work behind the future keeps running, so the other half of the pattern is a real cancellation (the Future lesson) or work that checks whether anyone still wants the result.
- orTimeout turns silence into a failure, so the chain routes into exceptionally or handle and the reader stops waiting on a stage that will never answer.
- completeOnTimeout turns silence into a value, which is right when a degraded answer beats none at all: a cached default, an empty list, a fallback page.
- A timeout can cover a whole chain. Attach it to the last stage and it measures the reader budget for everything behind it, which is usually the number a request has to respect.
- The delayed family joins this lesson to the scheduler one.
CompletableFuture.delayedExecutor(delay, unit, scheduler)turns a ScheduledExecutorService into an Executor you can hand to supplyAsync, which is how retries and backoff are written without sleeping; with no executor it is backed by a daemon-threaded scheduler the JDK keeps, with remove-on-cancel already switched on.
A timeout completes the reader, not the work: pair it with cancel when the work is expensive.
Rules that keep chains readable
A chain is easy to read while it is short and honest, and it stops being both the moment failures, blocking calls and stage counting pile up. These five rules prevent most of that.
- Name the boundary. A chain should start at an I/O call and end where the value is needed; one that mixes parsing, validation, caching and rendering hides where the failure policy applies.
- Decide where failure stops. One handle or exceptionally per boundary, or an explicit decision that the caller receives the CompletionException. A chain with no handler anywhere is a chain whose failures are invisible.
- Keep blocking out of the pipeline.
ExecutorService.submitinside a chain returns a Future you would have to block on; use supplyAsync or thenCompose with another stage instead. - Use the finished futures in tests. completedFuture(value) and failedFuture(throwable) remove the timing so a test exercises the error path on purpose rather than by accident.
- Do not treat the chain as a transaction. No stage is rolled back when a later one fails: compensation is application work, and it has to be written somewhere you can see it.
A chain is the same code you would have written with callbacks, with the failure path made explicit.
The rules in one place
Four shapes, one thread rule, and a failure that travels as a value.
- thenApply maps, thenCompose flattens, thenCombine joins, thenAccept ends, and allOf or anyOf aggregate many futures into one stage.
- Plain stages run on the completing thread or the caller; Async stages run on your executor or the common pool, which is never a place to block.
- exceptionally recovers, handle always runs, whenComplete only observes, and a failure that nothing absorbs reaches join() as a CompletionException.
- Timeouts complete the reader. orTimeout fails the future, completeOnTimeout fills it with a fallback, and neither stops the work underneath.
Describe the chain, read it once at the edge, and make the failure path explicit on the way.
A chain nobody reads still runs and still fails
CompletableFuture is eager: attaching a stage starts the machinery, and a failure completes the following stages exceptionally whether or not the final join ever happens. Without one handle or whenComplete that logs, the terminal stage that never ran leaves nothing behind except a silent exception inside a future nobody holds. Read at the edge, or observe inside the chain.
Interview angles
thenApply or thenCompose?+
thenApply maps a value: the function returns a plain value and the chain stays one level deep. thenCompose is for a function that returns another future, and it flattens the result so the type stays CompletableFuture<T>.
Common misconception: That the two are interchangeable because both take a function. Using thenApply with a future-returning function produces CompletableFuture<CompletableFuture<T>>, and the chain stops there until somebody unwraps it.
Follow-up: What breaks if thenApply is used where thenCompose belongs?
Which thread runs a callback?+
A plain stage runs on the thread that completes the upstream stage, or on the caller that completes it. Async stages run on the supplied executor, or on ForkJoinPool.commonPool when none is supplied. If the upstream value already exists, a plain stage runs on the attaching thread.
The common pool has parallelism of available processors minus one and is shared with parallel streams, so blocking inside an Async stage without an executor starves unrelated work.
exceptionally, handle, whenComplete: what is the difference?+
exceptionally recovers and runs only on failure. handle always runs, receives the value or the exception, and can recover or transform either outcome. whenComplete observes and keeps the outcome, so a failure continues downstream.
whenComplete is for logging and metrics. An action that throws inside it replaces the outcome only when the upstream had not already failed, so it is not a recovery mechanism.
What does allOf return, and what does it hide?+
CompletableFuture<Void>. It completes when every input is done, and if any failed, the combined future completes exceptionally with one of those failures. Every other outcome is still stored in its own future, so read each one to build a complete picture.
The empty cases are worth knowing: allOf with no arguments is already complete, while anyOf with no arguments returns a future that never completes. anyOf also returns its first outcome typed as Object, and a failure counts as an outcome.
orTimeout or cancel: which stops the work?+
cancel does, subject to the body cooperating with the interrupt. orTimeout completes the future with a TimeoutException and leaves the work running. The two are complementary: the timeout decides when the reader gives up, the cancel decides the work.
Follow-up: How would a retry with backoff be built from these two ideas?
Is a CompletableFuture lazy, like a stream pipeline?+
No. Stages start as soon as their inputs exist, whether or not the final result is ever read, and a failure is stored in the chain even when nobody looks at it. A stream runs nothing until its terminal operation; this class does the opposite.