Quick revision
The short answer
CompletableFuture.allOf waits for all three calls but does not stop when one fails, and cancelling the others does not interrupt their running work, so fail-fast needs extra code. invokeAll with a timeout also waits for every task and never stops early on the first failure. StructuredTaskScope (a preview API whose shape changed across JDK releases) fits the requirement best: it runs the calls as subtasks of one scope, fails fast on the first failure, cancels the rest by interrupting them, and never leaves work running after the scope closes. In every option the downstream clients still need their own timeouts.
What to remember
In this answer, we compared three ways to fan out to three services with fail-fast, cancellation and a 2-second limit. CompletableFuture.allOf waits for everything and needs extra code to fail fast, and its cancel does not interrupt running work. invokeAll enforces the timeout and cancels at the deadline, but never stops early on the first failure. StructuredTaskScope, a preview API that changed across releases, matches the requirement directly: it fails fast, interrupts the siblings and guarantees that no subtask outlives the scope, while keeping the call tree visible in thread dumps and passing ScopedValues to children. In every case, the downstream clients need their own timeouts, because cancellation only works when the call responds to interruption.
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.
CompletableFuture.allOf waits for all three calls but does not stop when one fails, and cancelling the others does not interrupt their running work, so fail-fast needs extra code. invokeAll with a timeout also waits for every task and never stops early on the first failure. StructuredTaskScope (a preview API whose shape changed across JDK releases) fits the requirement best: it runs the calls as subtasks of one scope, fails fast on the first failure, cancels the rest by interrupting them, and never leaves work running after the scope closes. In every option the downstream clients still need their own timeouts.
Why this question is asked
Fan-out is one of the most common shapes in service code: a request needs data from a profile service, a pricing service and an inventory service, and calling them one after another would triple the latency. The hard part is not starting three calls, it is the unhappy path: one call fails or hangs, and we must answer quickly and not leave the other two calls running and wasting resources. Interviewers ask this to see whether we know what each Java tool actually does on failure and cancellation, not only on success. In this answer, we will state the requirements precisely, try each of the three tools against them, see why structured concurrency matches them, and finish with the timeouts that every option still needs.
1The Requirements, Stated Precisely
We call services A, B and C in parallel. If all three succeed, we combine their results. If any one fails, we return an error immediately, without waiting for the others, and we cancel the others so they stop using threads, connections and downstream capacity. And whatever happens, the handler returns within 2 seconds.
Each tool below is judged on three questions: does it fail fast, does it really cancel the remaining work, and does it enforce the 2-second limit. It helps to recall what cancel means in Java. Cancelling a Future marks it cancelled, and for a FutureTask with cancel(true) it also interrupts the thread running it. Interruption is a request, not a kill: the running code must notice it, for example because it is blocked in an interruptible call, and stop.
2Option 1: CompletableFuture.allOf
allOf returns a future that completes when all given futures complete. If one fails, the combined future does fail, but only after all the others have finished too, because it waits for every one of them. So by itself it is not fail-fast.
With that extra code we get fail-fast and the 2-second limit through orTimeout. But there is a catch: CompletableFuture.cancel(true) does not interrupt the thread that runs the supplier. The documentation says the mayInterruptIfRunning flag has no effect, because a CompletableFuture is not tied to the thread computing it. So the slow call to service B keeps running in the background after we have already returned an error. To really stop it we would have to keep the underlying Future from the executor, or rely on B's client timeout.
3Option 2: ExecutorService.invokeAll
invokeAll(tasks, 2, SECONDS) runs the three callables and waits until all of them are done or the time runs out, and then cancels with interruption any task still running. That gives us the time limit and real cancellation at the deadline.
What it does not give us is fail-fast. If service A fails after 50 ms, invokeAll keeps waiting for B and C, possibly the full 2 seconds, before returning. The failure is only visible when we call get() on A's future afterwards. invokeAny is the opposite tool: it returns the first success, which is useful for hedged requests but not for needing all three. A CompletionService loop can build fail-fast on top of an executor, but that is again hand-written coordination code.
4Option 3: Structured Concurrency With StructuredTaskScope
Structured concurrency treats the three calls as children of one block of code. We open a scope, fork a subtask for each call, and join the scope. The rule is that no subtask outlives the scope: by the time the try block ends, every child has finished or been cancelled. Each subtask runs in its own virtual thread by default, so blocking calls are cheap.
The API is a preview feature, and it changed shape between releases. In JDK 21 to 24 we created a StructuredTaskScope.ShutdownOnFailure and called throwIfFailed() after join(). In JDK 25 (JEP 505) we call StructuredTaskScope.open() with a Joiner, and the default joiner already fails on the first failure. The snippet below follows the JDK 25 shape and needs --enable-preview; check your version for the exact names.
9 messages in order. Play them, or step through them one at a time.
The first failure cancels the siblings, and the scope does not close until they have stopped.
When A fails, the joiner cancels the scope at once: B and C are interrupted, join() throws a FailedException whose cause is A's exception, and the handler can return an error within milliseconds. When the 2 seconds pass first, join() throws a timeout exception and the scope cancels all running subtasks. Notice that we wrote no coordination code at all; failure, cancellation and the deadline are properties of the scope.
5Why Structure Also Helps Debugging
Structured concurrency keeps the parent-child relationship visible to tools. A thread dump in JSON format (jcmd <pid> Thread.dump_to_file -format=json dump.json) groups the subtasks under their scope, so we can see that three virtual threads belong to this one request. With executors and CompletableFuture chains, the work is spread across pool threads with no record of who started it.
Scopes also work with ScopedValue, a newer way to share immutable context such as a request id or the current user with code called deeper down. Values bound in the parent are inherited by the forked subtasks automatically, which ThreadLocal does not do for pooled threads.
6Timeouts on the Clients Are Still Required
In all three options, cancellation depends on interruption, and interruption only stops code that responds to it. A blocking JDBC call, or an HTTP client that is reading from a socket, may ignore interruption and keep the virtual or platform thread busy until the remote side answers. So the scope may wait at close for a call that will not stop.
That is why each downstream client gets its own timeout below the 2-second budget, for example a 300 ms connect timeout and a 1,500 ms read timeout on the HTTP client and a query timeout on JDBC. The scope or future gives us fail-fast and cancellation logic, and the client timeouts guarantee that cancelled or slow calls actually end.
| Tool | Fail fast | Cancels the rest | 2 s limit |
|---|---|---|---|
CompletableFuture.allOf | only with extra code | cancel() does not interrupt | orTimeout |
invokeAll(tasks, 2, SECONDS) | no, waits for all | yes, at the deadline | built in |
StructuredTaskScope | yes (default joiner) | yes, interrupts siblings | scope timeout |
7Follow-up questions
Can we use StructuredTaskScope in production today?
It is a preview API in current JDKs, which means it needs --enable-preview and may change in the next release, as it already did in JDK 25. Some teams accept that in internal services and keep the code in one small helper so an API change touches one place. Others use the same idea with an executor and a small utility class until the API is final.
What about reactive libraries such as Reactor's Mono.zip?
Mono.zip does fail fast and cancels the other sources when one errors, and with a non-blocking HTTP client the cancellation really stops the call. It is a good fit if the service is already reactive. For blocking code on virtual threads, structured concurrency gives the same behaviour with ordinary sequential-looking code, which is easier to read and debug.
Why is cancel(true) on a CompletableFuture not enough?
Because a CompletableFuture is just a result holder; it does not know which thread computes its value. Cancelling it completes it with a CancellationException, so dependent stages see the cancellation, but the supplier keeps running on its pool thread until it finishes on its own.
8Conclusion
In this answer, we compared three ways to fan out to three services with fail-fast, cancellation and a 2-second limit. CompletableFuture.allOf waits for everything and needs extra code to fail fast, and its cancel does not interrupt running work. invokeAll enforces the timeout and cancels at the deadline, but never stops early on the first failure. StructuredTaskScope, a preview API that changed across releases, matches the requirement directly: it fails fast, interrupts the siblings and guarantees that no subtask outlives the scope, while keeping the call tree visible in thread dumps and passing ScopedValues to children. In every case, the downstream clients need their own timeouts, because cancellation only works when the call responds to interruption.
Open with
I would judge each option on fail-fast, real cancellation and the deadline. CompletableFuture.allOf waits for all futures, so if A fails at 50 milliseconds it still waits for B and C.
Then, if they want more
I can add code so the first failure completes the combined future exceptionally, and orTimeout gives the 2 seconds, but cancel(true) on a CompletableFuture does not interrupt the running supplier, so the other calls keep running. invokeAll with a 2-second timeout cancels unfinished tasks with interruption at the deadline, but it never returns early on the first failure.
Structured concurrency matches the requirement best. I open a StructuredTaskScope, fork the three calls as subtasks on virtual threads, and join. With the default joiner in JDK 25, or ShutdownOnFailure in earlier previews, the first failure cancels the scope, interrupts the siblings, and join throws, and a scope timeout covers the 2 seconds.
The scope cannot close while a child is still running, the relationship shows up in thread dumps, and ScopedValues are inherited. It is still a preview API, so I would wrap it in a small helper.
And in every option I would set connect and read timeouts on the HTTP and JDBC clients below the budget, because interruption only works if the client responds to it.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 25, Java 21
- 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 "A request handler fans out to three downstream services in parallel and must return when...": https://scrivio-interview-library.netlify.app/java/threads/cc11c5d345/