Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Rewrite this blocking code as a non-blocking CompletableFuture chain using an executor ioPool:

Java
User u = userClient.get(id);
Account a = accountClient.get(u.accountId());
return render(u, a);

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.

Java
Page page(String id) {
User u = userClient.get(id); // blocks about 40 ms
Account a = accountClient.get(u.accountId()); // blocks about 60 ms, needs u
return render(u, a); // needs both u and a
}
// the calling thread is busy for about 100 ms, doing nothing but waiting

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.

Java
CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userClient.get(id), ioPool);
// returns at once; userClient.get runs on an ioPool thread

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.

Java
CompletableFuture<CompletableFuture<Account>> nested =
user.thenApply(u -> CompletableFuture.supplyAsync(() -> accountClient.get(u.accountId()), ioPool));
// compiles, but the type is a future of a future: awkward and easy to misuse
thenApply versus thenCompose
MethodFunction returnsResult type
thenApply(u -> account(u))AccountCompletableFuture<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.

Java
CompletableFuture<Page> page(String id) {
return CompletableFuture.supplyAsync(() -> userClient.get(id), ioPool) // future of User
.thenCompose(u ->
CompletableFuture.supplyAsync(() -> accountClient.get(u.accountId()), ioPool) // future of Account
.thenApply(a -> render(u, a))); // u and a both in scope
}
// page("42") returns immediately: a CompletableFuture<Page>
// about 100 ms later it completes with the rendered page
Step throughHow the chain runs
CallerioPool thread 1ioPool thread 2Services
supplyAsync: userClient.get(id)
returns CompletableFuture<Page> at once
GET /users/42
User (40 ms)
thenCompose: supplyAsync accountClient.get
GET /accounts/7
Account (60 ms)
thenApply: render(u, a), completes the page future

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.

Java
@GetMapping("/users/{id}/page")
CompletableFuture<Page> show(@PathVariable String id) {
return page(id)
.orTimeout(2, TimeUnit.SECONDS) // fail after 2 s
.exceptionally(e -> Page.unavailable()); // timeout or client error -> fallback page
}

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.

What to say in the interviewAbout 100 seconds aloud

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.
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/