Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

This code calls three services and is slow:

Java
List<Future<R>> fs = new ArrayList<>();
for (Call c : calls) {
Future<R> f = pool.submit(c);
fs.add(f);
f.get();
}

Explain and fix, and mention invokeAll and invokeAny.

The loop calls get() immediately after each submit, so it waits for each call to finish before submitting the next one, and the three calls run one after another even though they use a pool. The fix is to submit all tasks first and only then loop over the futures calling get, preferably with a timeout so a stuck call cannot block forever. invokeAll does both steps in one call and accepts an overall timeout that cancels unfinished tasks, while invokeAny returns the result of one task that completes successfully and cancels the rest.

Why this question is asked

Calling several services at once to build a response is one of the most common reasons for using an executor, and this bug is one of the most common ways to get no benefit from it. The code looks parallel, there is a pool and there are futures, yet the timing is the sum of the calls rather than the slowest one. Interviewers like it because it checks whether we understand what Future.get() actually does. In this answer, we will see why the loop is sequential, fix it, measure the difference, add timeouts, and then use invokeAll and invokeAny, with a word on the newer alternatives.

1A Quick Recap of submit and Future.get

ExecutorService.submit(task) hands a task to the pool and returns immediately with a Future, an object that represents a result that will exist later. Calling future.get() blocks the calling thread until the task has finished, then returns its result or throws an ExecutionException wrapping the task's exception.

So submit starts work, and get waits for it. The order in which we call them decides whether tasks overlap.

2Why the Loop Runs Sequentially

Look at the loop body: submit, add, get. The get() call waits for the task we just submitted. Only when it returns does the loop move on and submit the next call. At any moment, at most one task is running, so the pool's other threads sit idle.

Java
// Broken: looks parallel, runs one call at a time
List<Future<R>> fs = new ArrayList<>();
for (Call c : calls) {
Future<R> f = pool.submit(c);
fs.add(f);
f.get(); // waits for this call before submitting the next
}
// calls take 300 ms, 400 ms and 500 ms -> total about 1,200 ms
Step throughSubmit then get, three times
Request threadPoolServices
submit call A
A runs, 300 ms
get() returns A
submit call B
B runs, 400 ms
get() returns B
submit call C
C runs, 500 ms
get() returns C, total 1,200 ms

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

Each get() blocks before the next submit, so the calls never overlap.

Notice that the futures list is built but never needed, because every result was already waited for inside the loop. That leftover list is a hint that the author meant to wait later and moved the get() by mistake.

3The Fix: Submit Everything, Then Wait

We split the loop in two. The first loop submits every call, so all three start at once. The second loop waits for each future in turn. Waiting for the first one takes 300 ms; by then the others have also been running for 300 ms, so the second get waits about 100 ms more and the third about another 100 ms. The total is the time of the slowest call, about 500 ms.

Java
List<Future<R>> fs = new ArrayList<>();
for (Call c : calls) {
fs.add(pool.submit(c)); // all three start now
}
List<R> results = new ArrayList<>();
for (Future<R> f : fs) {
results.add(f.get(2, TimeUnit.SECONDS)); // waits at most 2 s for each
}
// total about 500 ms: the slowest call, not the sum

The timeout matters. A plain get() waits forever, so one downstream that never answers would hold the request thread indefinitely. With get(2, SECONDS), a stuck call ends in a TimeoutException, and we should then cancel it with f.cancel(true), which interrupts the task's thread, and decide whether to fail the request or return a partial result. Notice that the timeouts add up: with three sequential get calls the worst case is 6 seconds, so for a strict overall deadline we compute the time left before each get.

4InvokeAll: Submit All, Wait for All

ExecutorService.invokeAll(tasks) does both loops in one call: it submits every task and returns only when all have completed, giving back the list of futures in the same order as the tasks. The overload with a timeout is especially useful: invokeAll(tasks, 1, SECONDS) waits at most one second in total, and any task not finished by then is cancelled, so its future reports isCancelled() and get() throws CancellationException.

Java
List<Callable<R>> tasks = List.of(callA, callB, callC);
List<Future<R>> done = pool.invokeAll(tasks, 1, TimeUnit.SECONDS); // returns within about 1 s
for (Future<R> f : done) {
if (f.isCancelled()) {
log.warn("call timed out"); // this one was cancelled at the deadline
} else {
results.add(f.get()); // already complete: get() does not block
}
}

Notice that get() can still throw ExecutionException for a task that failed rather than timed out, so the loop should handle that as well. One overall deadline is usually what a request handler needs, because it maps directly onto the request's own timeout.

5InvokeAny: The First Successful Result

invokeAny(tasks) solves a different problem. It runs the tasks and returns the result of one that completes successfully, cancelling the others. If all of them fail, it throws an ExecutionException. This fits redundant requests: asking two replicas or two regions for the same data and taking whichever answers first, or trying several equivalent providers.

Java
String price = pool.invokeAny(List.of(askRegionEu, askRegionUs), 800, TimeUnit.MILLISECONDS);
// the first successful answer wins, for example from EU after 120 ms; the US call is cancelled

Because it cancels the losers, invokeAny works best when the tasks respond to interruption, for example blocking I/O that honours interrupts, otherwise the cancelled tasks keep running in the background and use pool threads.

6Newer Alternatives

CompletableFuture offers the same fan-out in a composable style: supplyAsync for each call, then CompletableFuture.allOf(...).orTimeout(1, SECONDS) to wait for all with a deadline. With virtual threads, structured concurrency through StructuredTaskScope goes further: subtasks are forked inside a scope that joins them and cancels the rest on failure, so no task outlives the request. StructuredTaskScope is still a preview API in recent Java releases and its shape has changed between versions, so check your version before using it. The principle is the same in every form: start all the independent calls first, then wait with a deadline.

7Follow-up questions

Does the pool size matter for the fix?

Yes. If the pool has fewer threads than concurrent calls across all requests, tasks queue and the parallelism disappears again under load. For I/O-bound calls like these, a virtual-thread-per-task executor avoids that, with concurrency limited by the downstream clients' connection pools.

What happens to a task when get times out?

Nothing, by itself. The task keeps running. We must call cancel(true) on the future to interrupt it, and the task only stops if its code reacts to interruption. invokeAll with a timeout does the cancelling for us.

Why not use parallelStream for the three calls?

Parallel streams run on the common ForkJoinPool, which is sized for CPU-bound work and shared by the whole JVM. Blocking network calls there can starve other users of the pool, and there is no timeout. An executor chosen for I/O, or CompletableFuture with an explicit executor, is the right tool.

8Conclusion

In this answer, we saw that calling get() right after each submit makes the calls run one after another, because get blocks until that task finishes. Submitting all tasks first and then collecting the futures turns the total time from the sum of the calls into the slowest call, and using get with a timeout, plus cancel, keeps a stuck call from blocking forever. invokeAll does submit-and-wait in one call with an overall deadline that cancels unfinished tasks, invokeAny returns the first successful result and cancels the rest, and CompletableFuture or structured concurrency express the same pattern in newer styles.

What to say in the interviewAbout 100 seconds aloud

Open with

The problem is the get inside the loop. submit returns immediately, but get blocks until that task is done, so the loop submits call one, waits for it, then submits call two, and so on.

Then, if they want more

Only one call ever runs at a time, and the total is the sum of the three, say 300 plus 400 plus 500 milliseconds, 1.2 seconds. The fix is to split it into two loops: first submit all the calls, so they all start together, then loop over the futures and collect the results.

Then the total is roughly the slowest call, about 500 milliseconds.

I'd also use get with a timeout rather than plain get, because plain get waits forever if a downstream hangs, and on timeout I'd cancel the future with cancel true and decide whether to fail or return partial data. invokeAll packages this: it submits all the tasks and waits for all of them, returning futures in order, and the overload with a timeout gives one overall deadline, cancelling whatever hasn't finished, which maps nicely onto the request's own timeout. invokeAny is for a different case: it returns the result of the first task that completes successfully and cancels the rest, which suits redundant calls, like asking two regions and taking the first answer.

In newer code I might write the same thing with CompletableFuture allOf and orTimeout, but the principle is the same: start everything first, then wait with a deadline.

About this answer

Last updated
12 November 2026
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 "This code calls three services and is slow:": https://scrivio-interview-library.netlify.app/java/executors/6abfce1d38/