Quick revision
The short answer
We start the user call with CompletableFuture.supplyAsync(() -> userClient.get(id), ioPool), then use thenCompose, because the account call depends on the user and itself returns a future: .thenCompose(u -> CompletableFuture.supplyAsync(() -> accountClient.get(u.accountId()), ioPool).thenApply(a -> render(u, a))). The nested thenApply keeps u in scope for render, and the method returns the future to its caller instead of calling join(), so no caller thread ever blocks.
What to remember
In this answer, we turned three blocking lines into a CompletableFuture chain. supplyAsync with ioPool starts the user call, thenCompose chains the account call because it depends on the user and returns a future of its own, and the thenApply nested inside the thenCompose keeps u in scope for render. The method returns the future instead of calling join(), and a timeout and a fallback make it production-ready, with ioPool sized for the blocking clients.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We start the user call with CompletableFuture.supplyAsync(() -> userClient.get(id), ioPool), then use thenCompose, because the account call depends on the user and itself returns a future: .thenCompose(u -> CompletableFuture.supplyAsync(() -> accountClient.get(u.accountId()), ioPool).thenApply(a -> render(u, a))). The nested thenApply keeps u in scope for render, and the method returns the future to its caller instead of calling join(), so no caller thread ever blocks.
Why this question is asked
Turning blocking code into a CompletableFuture chain is a very common task when a service moves to asynchronous request handling, and it is a good interview exercise because the obvious first attempt usually has a type error or blocks after all. The three lines of the original code hide three ideas: running the first call asynchronously, chaining a call that depends on the first result, and keeping both results available at the end. In this answer, we will look at the blocking version, build the chain one step at a time, see why thenCompose is needed and why the thenApply is nested, and finish with timeouts, errors and what non-blocking really means here.
1The Blocking Version and What We Want
Here is the starting point. Each line waits for the previous one, and the thread running it is blocked during both remote calls.
Notice the dependencies. The account call needs u.accountId(), so it cannot start until the user call finishes; the two calls cannot run in parallel. And render needs both u and a. The goal is a method that returns at once with a CompletableFuture<Page>, runs the calls on the ioPool executor, and completes the future when the page is ready.
2Start the First Call Asynchronously
supplyAsync takes a Supplier, a function with no arguments that returns a value, and runs it on the executor we pass. It returns immediately with a future that will hold the user.
We pass ioPool explicitly. Without it, the blocking client call would run on ForkJoinPool.commonPool(), which is shared by the whole JVM and is not meant for blocking work.
3Why thenApply Is Not Enough
The natural next step is thenApply, which transforms a result. Let us try it.
| Method | Function returns | Result type |
|---|---|---|
thenApply(u -> account(u)) | Account | CompletableFuture<Account> |
thenApply(u -> accountAsync(u)) | CompletableFuture<Account> | CompletableFuture<CompletableFuture<Account>> |
thenCompose(u -> accountAsync(u)) | CompletableFuture<Account> | CompletableFuture<Account> |
Because our function itself returns a CompletableFuture<Account>, thenApply wraps it in another future, giving a CompletableFuture<CompletableFuture<Account>>. To get the account we would have to unwrap it, and the tempting way, calling join() inside, blocks a thread again.
thenCompose solves exactly this. It takes a function that returns a future and flattens the result: when the user arrives, it calls our function, and the future it returns completes when the inner future completes. It is the asynchronous version of calling one method after another, where the second call depends on the first. In other APIs this operation is often called flatMap.
4The Full Chain, With u Still in Scope
Now we need render(u, a). If we wrote user.thenCompose(u -> accountAsync(u)).thenApply(a -> render(u, a)), it would not compile, because u only exists inside the first lambda. The fix is to put the thenApply inside the thenCompose lambda, on the inner future, where u is still in scope.
8 messages in order. Play them, or step through them one at a time.
The caller is free from the first line; pool threads do the waiting.
Read it from the outside in. The outer future gives us u. For that u, we start the account call and, on its future, map the account a to render(u, a). thenCompose then flattens that inner CompletableFuture<Page> into the CompletableFuture<Page> the method returns.
Notice which thread runs render: the plain thenApply runs on the ioPool thread that completed the account call. That is fine because render is quick. If render were heavy, we would use thenApplyAsync with a CPU executor instead.
5Return the Future, Not join()
The last rule is to return the future to the caller. If the method ended with .join(), it would block the calling thread until the page was ready, and we would be back to the original blocking code, now with extra threads involved. The caller decides what to do with the future: a Spring MVC controller can return CompletableFuture<Page> directly, and Spring completes the HTTP response when the future completes, freeing the request thread in the meantime.
Real code also needs a time limit and error handling. orTimeout, available since Java 9, completes the future exceptionally if it takes too long, and exceptionally or handle turns failures into a fallback.
One honest caveat: this chain is non-blocking for the caller, but userClient.get and accountClient.get are still blocking calls, so ioPool threads wait during them. That is why ioPool must be sized for I/O, or be a virtual-thread executor. If the clients offer asynchronous methods that already return CompletableFuture, we use those directly inside thenCompose and no thread waits at all.
6Follow-up questions
What if the two calls were independent?
Then we would start both with supplyAsync and combine them with thenCombine, for example userF.thenCombine(accountF, this::render), so the calls run in parallel and the total time is the slower of the two instead of their sum.
Why not use thenApplyAsync for render?
We could, but it adds a task hand-off for a quick function. The plain thenApply runs render on the ioPool thread that finished the account call, which is fine for short work. For heavy rendering, thenApplyAsync with a CPU executor keeps I/O threads free.
How do exceptions travel through this chain?
If userClient.get throws, the first future completes exceptionally, thenCompose skips our function, and the returned future completes exceptionally with a CompletionException wrapping the original. The exceptionally stage at the end sees it and returns the fallback.
7Conclusion
In this answer, we turned three blocking lines into a CompletableFuture chain. supplyAsync with ioPool starts the user call, thenCompose chains the account call because it depends on the user and returns a future of its own, and the thenApply nested inside the thenCompose keeps u in scope for render. The method returns the future instead of calling join(), and a timeout and a fallback make it production-ready, with ioPool sized for the blocking clients.
Open with
I would write it as one chain that returns a CompletableFuture of Page. It starts with CompletableFuture.supplyAsync of a lambda calling userClient.get(id), passing ioPool, so the blocking client call runs on our I/O executor and not the common pool.
Then, if they want more
The account call depends on the user, and it also produces a future, so the next step is thenCompose, not thenApply. With thenApply, a function that returns a future would give me a future of a future; thenCompose flattens it, it is the async version of calling one method after the other.
Inside the thenCompose lambda I start the account call with supplyAsync of accountClient.get(u.accountId()), again on ioPool, and on that inner future I call thenApply with a lambda a to render(u, a). The thenApply has to be nested there, because that is the only place where both u and a are in scope; chaining it outside would not compile.
The method returns that future directly; I would not call join, because that would block the caller and undo the whole point. In a Spring MVC controller I can return the CompletableFuture and Spring writes the response when it completes. I would add orTimeout and exceptionally for a fallback.
One caveat I would mention: the clients are still blocking, so ioPool threads wait during the calls and ioPool must be sized for I/O or use virtual threads. If the clients had async APIs returning futures, I would use them inside thenCompose instead. And if the two calls were independent, I would use thenCombine so they run in parallel.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Rewrite this blocking code as a non-blocking CompletableFuture chain using an executor...": https://scrivio-interview-library.netlify.app/java/completable-future/9f191ffb84/