CompletableFuture and asynchronous programming in Java
Calling three services in parallel the right way: choosing the executor (the common ForkJoinPool trap), thenApply/thenCompose/thenCombine/allOf/anyOf, unwrapping CompletionException, timeouts and the limits of cancel, carrying MDC/SecurityContext, Spring @Async proxy traps, when virtual threads are simpler, structured concurrency from preview to final in JDK 28; how to review async code written by AI.
On this page
1. The problem
A dashboard API calls profile (300 ms), orders (500 ms) and points (200 ms) one after another: the user waits 1,013 ms. Switching to supplyAsync without an executor gets 506 ms on a laptop, but under load the whole JVM chokes on the common pool. Adding orTimeout makes the log say "timeout" while the thread still hangs on the socket.
2. Key idea
Parallel calls turn "total time" into "the slowest branch", but every branch still holds a thread and a connection. A future is just a claim ticket: tearing it up doesn't make the worker stop. Work only stops when the I/O has a timeout or the task checks a cancellation flag.
Before fanning out, answer four questions: are the branches independent, which threads do they run on, where does the timeout live, which branches may be missing (degrade). Branch timeout < API timeout < caller timeout.
| Choice | Use when | Don't use when |
|---|---|---|
| Sequential calls | a later branch needs an earlier result, or it's already fast enough | branches are independent and latency is a measured problem |
| CF with a dedicated executor | the API is already async (HttpClient.sendAsync), per-step timeouts |
new Java 21+ code that just needs "call three places and merge" |
| Virtual threads + blocking code | new business code on Java 21+ | heavy computation; downstreams without concurrency limits |
| Structured concurrency | one branch failing must really cancel the rest | your JDK lacks the final version and you won't accept preview |
3. In Java
// io: a dedicated executor (bounded pool or virtual threads), not the common pool
List<String> degraded = Collections.synchronizedList(new ArrayList<>());
var p = CompletableFuture.supplyAsync(() -> profileClient.get(id), io); // required
var o = CompletableFuture.supplyAsync(() -> orderClient.of(id), io) // client has a read timeout
.exceptionally(ex -> { degraded.add("orders"); return List.of(); });
var pt = CompletableFuture.supplyAsync(() -> pointsClient.of(id), io)
.exceptionally(ex -> { degraded.add("points"); return 0; });
return CompletableFuture.allOf(p, o, pt)
.orTimeout(1, TimeUnit.SECONDS) // frees the waiter, doesn't stop the tasks
.thenApply(v -> new Dashboard(p.join(), o.join(), pt.join(), List.copyOf(degraded)))
.join(); // errors are wrapped: unwrap(ex) before checking typeOther languages: Go uses errgroup.WithContext, where one failing goroutine cancels ctx for the others; Node.js Promise.all fails fast but doesn't cancel the other promises, so pass an AbortController.
Composing steps, exceptions, context and @Async
thenApply: transform the result.thenCompose: the next step returns another CF (avoidsCF<CF<T>>).thenCombine: merge two independent CFs.anyOf: take whichever finishes first.- Errors in a chain reach you as
CompletionException(orExecutionExceptionwithget()); takegetCause()before checkinginstanceof. exceptionally(ex -> null)at the end swallows every error; put the fallback right after the optional branch.- MDC and
SecurityContextare bound to threads: use aTaskDecoratoror Context Propagation to carry them to the executor. @Asyncworks through a proxy: callingthis.method()in the same class runs synchronously. ReturnCompletableFuture<T>rather thanvoidso errors don't vanish.- Callbacks without the
Asyncsuffix may run on whatever thread completed the previous CF, including an I/O thread.
4. Working with AI
Hand to AI: a fan-out skeleton with tests simulating per-branch latency, an unwrap helper with tests, converting a CF chain to virtual threads and comparing measurements.
Check yourself in AI-written code:
- Every
supplyAsync,runAsync,...Asynchas an executor; greppingAsync(finds none without it. - HTTP/JDBC clients have connect and read timeouts;
orTimeoutisn't the only protection. - No
exceptionally(ex -> null)at the end of a chain; errors are unwrapped before type checks. - Executors have thread names, bounded queues and a busy-thread metric.
- Logs in async tasks keep the trace id;
@Asyncisn't called throughthis.
5. Exercises
Exercise 1: Review a dashboard "with timeouts and degrade"
Requirements: profile is required; orders and points are optional, at most 800 ms each, and on failure or timeout return empty and record their name in degraded. Simulation: orders hangs 2 s, points throws 503. The AI says "the 800 ms timeout protects the pool". Find two bugs, name a test, fix it.
var p = CompletableFuture.supplyAsync(Exercise::profile);
var o = CompletableFuture.supplyAsync(Exercise::orders)
.orTimeout(800, TimeUnit.MILLISECONDS)
.exceptionally(ex -> List.of());
var pt = CompletableFuture.supplyAsync(Exercise::points).exceptionally(ex -> 0);
return CompletableFuture.allOf(p, o, pt)
.thenApply(v -> new Dashboard(p.join(), o.join(), pt.join(), List.of())).join();Solution 1
- No executor: all three branches run on the common pool;
ordershanging 2 s holds a common-pool thread, and under load the whole JVM chokes. orTimeoutonly frees the waiter: theordersthread still hangs for 2 s, so "protects the pool" is false. The 800 ms timeout belongs in the HTTP client's read timeout.- Also:
degradedis always empty, andprofilehas no timeout. - Test: simulate
ordershanging, fire 20 concurrent requests, measure busy executor threads after 1 s; assertdegradedcontainsorders. - Fix as in section 3: a dedicated executor, a client with an 800 ms read timeout, fallbacks that record
degraded,orTimeoutonprofile.
Exercise 2: Choose how to "fail fast on one branch"
allOf waits for every branch even after one has failed. You need allOrFail: if one branch fails, report immediately and cancel the rest. The AI offers: (A) hand-written with whenComplete + cancel(true); (B) StructuredTaskScope. The service runs JDK 21. Which one, and what would flip the choice?
Solution 2
- JDK 21 without preview: pick A, knowing that
cancel(true)on a CF doesn't interrupt the task, so slow tasks run to completion. To really free threads, tasks need timeouts at the I/O layer. - B really cancels through interrupts, but on JDK 21 it's a preview and the API changed between releases. Pick B once you're on a JDK where structured concurrency is final.
- If you already use virtual threads and blocking code, B is much simpler: no
unwrap, no hand-wiredwhenComplete.
Summary
- Parallel: time ≈ the slowest branch, if the branches are truly independent.
- Always pass an executor; never run I/O on the common pool.
orTimeoutandcanceldon't stop the underlying work: real timeouts live in the client.- Fallbacks right after optional branches; unwrap
CompletionException. - Java 21+: virtual threads with blocking code are often simpler than CF chains.
Further reading: ExecutorService and virtual threads.
Practice interview questions on this topic
- How do Future and CompletableFuture differ? When do you use thenApply, thenCompose and thenApplyAsync?
- What are the pitfalls of @Async in Spring? Why does an @Async method still run synchronously?
- Your API calls three services in parallel and one occasionally hangs. How do you design it?
- How does ThreadLocal leak in a thread pool? Why do async logs lose the trace id?
- What do Java 21 virtual threads help with, what don't they, and do you still need CompletableFuture?
Comments
Community rules