Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Call two remote services in parallel with CompletableFuture, combine their results, and fail the whole operation if it takes longer than 2 seconds. Which executor do you use?

Start each remote call with CompletableFuture.supplyAsync(() -> client.call(), executor), passing a dedicated executor for blocking I/O rather than the common ForkJoinPool, combine the two with a.thenCombine(b, (x, y) -> merge(x, y)), and apply orTimeout(2, TimeUnit.SECONDS) to the combined future so the whole operation fails with a TimeoutException after two seconds; completeOnTimeout gives a fallback value instead. Failures are handled with exceptionally or handle. Timing out the future does not stop the underlying calls, so each client also needs its own timeouts.

Background to this question

A page or API response often needs data from two or three services, and calling them one after another adds their latencies together. CompletableFuture lets us run them in parallel and combine the results, and this is a very common coding question because the short solution hides several decisions: which threads run the calls, how failures and timeouts surface, and what really happens to a call after we stop waiting for it. In this answer, we will write the sequential version and its cost, run the calls in parallel on the right executor, combine them, add the two-second limit, handle failures, and see why the clients still need timeouts of their own.

1The Sequential Version and Its Cost

Suppose a dashboard needs a customer's profile from one service and their recent orders from another. The profile call takes about 300 ms and the orders call about 500 ms.

Java
Profile profile = profileClient.get(customerId); // 300 ms
List<Order> orders = orderClient.recent(customerId); // 500 ms
Dashboard d = new Dashboard(profile, orders); // total: about 800 ms

The two calls are independent, so there is no reason for the second to wait for the first. Run in parallel, the total is the slower of the two, about 500 ms. That is the whole motivation for CompletableFuture here: a future is an object that will hold a result later, and CompletableFuture lets us attach what should happen when the result arrives instead of blocking for it.

2Running Both Calls in Parallel on the Right Executor

supplyAsync runs a supplier, a function that returns a value, on another thread and returns a CompletableFuture that completes with that value. It has two forms: without an executor it uses ForkJoinPool.commonPool(), and with an executor it uses that one. For blocking I/O, always pass an executor.

Java
// Java 21+: a virtual thread per task suits blocking calls
private final ExecutorService io = Executors.newVirtualThreadPerTaskExecutor();
// Before Java 21: a bounded, named platform pool, e.g. 50 threads with a bounded queue
CompletableFuture<Profile> profileF =
CompletableFuture.supplyAsync(() -> profileClient.get(customerId), io);
CompletableFuture<List<Order>> ordersF =
CompletableFuture.supplyAsync(() -> orderClient.recent(customerId), io);
// both calls are now running at the same time

The reason to avoid the common pool is its size and its sharing. It has roughly as many threads as cores minus one, perhaps 7 on an 8-core machine, and the whole JVM shares it with parallel streams and every other async call that omits an executor. Blocking HTTP calls hold those threads while they wait, so a handful of concurrent dashboards would exhaust it and stall unrelated code. A dedicated executor isolates this work: virtual threads on Java 21 and later make blocking cheap, and on older versions a bounded platform pool sized for the expected concurrency does the job.

3Combining the Results and Adding the Two-Second Limit

thenCombine waits for two futures and passes both results to a function. The returned future completes when both inputs have completed, or exceptionally as soon as either fails. orTimeout, added in Java 9, makes a future complete exceptionally with a TimeoutException if it has not completed within the given time.

Java
CompletableFuture<Dashboard> dashboardF = profileF
.thenCombine(ordersF, (profile, orders) -> new Dashboard(profile, orders))
.orTimeout(2, TimeUnit.SECONDS);
Dashboard d = dashboardF.join();
// normal case: returns after about 500 ms
// orders slow: throws CompletionException caused by TimeoutException after 2 s
// profile fails: throws CompletionException caused by the client's exception
Step throughTwo calls in parallel with an overall timeout
CallerVirtual threadsProfile serviceOrder service
supplyAsync x 2 on the io executor
get(customerId)
recent(customerId)
profile after 300 ms
orders after 500 ms
thenCombine: Dashboard at about 500 ms
orTimeout(2 s) fails the combined future if still incomplete

7 messages in order. Play them, or step through them one at a time.

The total is the slower call, and the timeout bounds the whole operation.

Notice where orTimeout is applied: on the combined future, so the two seconds cover the whole operation, which is what the question asks for. Applying it to each call separately would let each take two seconds but still bound the total to two seconds because they run in parallel; the combined form states the requirement directly. join() waits for the result and wraps any failure in an unchecked CompletionException, while get() throws the checked ExecutionException and InterruptedException instead.

If a partial answer is better than none, completeOnTimeout supplies a fallback value instead of failing. For example, ordersF.completeOnTimeout(List.of(), 1500, TimeUnit.MILLISECONDS) lets the dashboard show the profile with an empty order list when the orders service is slow.

4Handling Failures

A failure can come from either call or from the timeout, and in a chain it arrives wrapped in a CompletionException. exceptionally runs only on failure and can return a replacement value or rethrow a domain exception; handle runs on both success and failure and receives both the result and the exception, one of them null.

Java
CompletableFuture<Dashboard> safe = dashboardF.exceptionally(ex -> {
Throwable cause = (ex instanceof CompletionException ce) ? ce.getCause() : ex;
if (cause instanceof TimeoutException) {
throw new DashboardUnavailableException("dashboard took longer than 2 s", cause);
}
throw new DashboardUnavailableException("dashboard failed", cause);
});

Because the requirement is to fail the whole operation, we translate the failure into an exception the web layer maps to a clear error response, rather than returning a fake dashboard. Unwrapping the CompletionException is a habit worth having, because otherwise logs and checks see the wrapper instead of the real cause.

5Why the Clients Still Need Their Own Timeouts

orTimeout completes our future; it does not stop the work behind it. The virtual thread running orderClient.recent is still blocked in the HTTP call after the dashboard has failed, and it will stay there until the call returns, holding a connection from the client's pool. Calling cancel(true) on a CompletableFuture does not interrupt the running task either; it only completes the future with a CancellationException. Under load, abandoned calls pile up, exhaust the connection pool, and make every later request slower.

So each client must have connect and read timeouts of its own, set a little below the overall budget, for example 1.5 seconds for each call within a 2-second operation. Then a slow call actually ends, frees its thread and connection, and fails its future, usually before orTimeout fires. The overall timeout becomes a safety net rather than the only limit.

6Follow-up questions

What is the difference between thenCombine and allOf?

thenCombine joins exactly two futures and passes both results to a function, giving a typed result. CompletableFuture.allOf takes any number of futures and returns a CompletableFuture<Void>, so we read each result afterwards with join(), which is safe because they are all complete. For two calls thenCombine is clearer; for a list of calls allOf is the tool.

Should the executor be shared across requests?

Yes, one executor per kind of work, created once and shut down with the application. Creating a new executor per request wastes threads and, for platform pools, leaks them if not shut down. A virtual-thread-per-task executor is cheap but still worth sharing so it can be closed on shutdown.

Would structured concurrency be an alternative?

Structured concurrency, which lets a scope fork subtasks and cancels the remaining ones when one fails or the scope times out, addresses exactly the abandoned-call problem. It has been a preview API in recent JDKs and its API has changed between releases, so check its status on your version before using it in production.

7Conclusion

In this answer, we ran two remote calls in parallel with supplyAsync on a dedicated executor for blocking I/O, virtual threads on Java 21 and later, instead of the common pool. We combined them with thenCombine, bounded the whole operation with orTimeout(2, TimeUnit.SECONDS) or used completeOnTimeout for a fallback, and handled failures with exceptionally, unwrapping the CompletionException. Because a timed-out future does not cancel the calls behind it, each client also needs its own connect and read timeouts.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start each call with CompletableFuture.supplyAsync, passing an executor, never relying on the common ForkJoinPool, because that pool is small, about cores minus one, and shared by the whole JVM, so blocking HTTP calls there would stall parallel streams and other async work.

Then, if they want more

On Java 21 I would use a virtual-thread-per-task executor; before that, a bounded named pool sized for the concurrency. Both calls are now running at the same time. Then profile.thenCombine(orders, (p, o) -> new Dashboard(p, o)) gives a future that completes when both are done, or fails as soon as either fails.

On that combined future I call orTimeout(2, TimeUnit.SECONDS), available since Java 9, so if the whole thing is not done in two seconds it completes with a TimeoutException. If a fallback were acceptable I would use completeOnTimeout instead, for example an empty order list.

I handle failures with exceptionally or handle, unwrapping the CompletionException and turning it into a domain exception that the controller maps to an error response. The important caveat is that the timeout only completes my future; it does not stop the underlying HTTP calls, and cancel does not interrupt them either.

So each client gets its own connect and read timeouts, a bit below the overall budget, so abandoned calls do not hold threads and connections.

About this answer

Last updated
12 November 2026
Versions it names
Java 21, 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 official documentation for the version you use. 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 "Call two remote services in parallel with CompletableFuture, combine their results, and...": https://scrivio-interview-library.netlify.app/java/concurrency-patterns/8005992b3c/