Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Start three worker threads that each process part of a list, and make the main thread wait for all of them, with a total time limit of 5 seconds. Show it with Thread.join, with CountDownLatch, and with ExecutorService.invokeAll. What happens if a worker throws?

With Thread.join we call join(remaining) on each thread while tracking one shared deadline, then check isAlive(), because join(long) returns quietly on timeout. With CountDownLatch each worker counts down in a finally block and the main thread calls await(5, SECONDS), which returns false on timeout. With ExecutorService.invokeAll(tasks, 5, SECONDS) we get a list of Futures; unfinished tasks are cancelled, and get() reports each task's exception as ExecutionException. If a worker throws, raw threads lose the exception to the uncaught exception handler unless we collect it, while futures carry it back to us.

Why this question is asked

Waiting for a group of threads with a time limit sounds like a beginner exercise, but it is where many real bugs hide: waits that never time out, timeouts that are silently ignored, and failures that vanish because nobody looked at them. Interviewers ask for all three approaches to see whether we understand what each one reports back and what it hides. In this answer, we will set up the task, solve it with join, with CountDownLatch and with invokeAll, look closely at what happens when a worker throws, and see why executors and futures are the preferred tool.

1Setting Up the Task

We have a list of items and three workers, each processing one third of it. The main thread must wait until all three finish, but never longer than 5 seconds in total. Notice the word total: if we give each wait its own 5 seconds, three waits could take 15 seconds. So every solution works from one deadline computed at the start.

We will use the same split and the same process() method in every version. The list has 9 items, so each worker gets 3.

Java
List<Integer> items = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
int parts = 3;
int size = items.size() / parts; // 3
List<List<Integer>> chunks = new ArrayList<>();
for (int i = 0; i < parts; i++) {
chunks.add(items.subList(i * size, (i + 1) * size)); // [1,2,3] [4,5,6] [7,8,9]
}
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);

2Version 1: Thread.join With a Shared Deadline

join() makes the calling thread wait until the target thread finishes. join(long millis) waits at most that long, and here is the trap: when the time runs out it simply returns, with no exception and no return value. The only way to know whether the thread finished is to call isAlive() afterwards.

Java
List<Throwable> errors = new CopyOnWriteArrayList<>();
List<Thread> threads = new ArrayList<>();
for (List<Integer> chunk : chunks) {
Thread t = new Thread(() -> process(chunk), "worker-" + threads.size());
t.setUncaughtExceptionHandler((th, ex) -> errors.add(ex)); // collect failures ourselves
threads.add(t);
t.start();
}
for (Thread t : threads) {
long remainingMs = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime());
if (remainingMs > 0) t.join(remainingMs); // returns on finish OR on timeout
}
boolean allDone = threads.stream().noneMatch(Thread::isAlive); // false if any is still running
System.out.println("done=" + allDone + " errors=" + errors.size()); // done=true errors=0

Each join uses only the time left before the deadline, so the total wait is at most 5 seconds. Notice also that a remaining time of 0 must be skipped, because join(0) means wait forever, which is the opposite of what we want.

If the time runs out, the late threads keep running. join does not stop anything; it only stops waiting. To stop them we must call interrupt() and the workers must respond to interruption.

3Version 2: CountDownLatch

A CountDownLatch is a counter that threads can wait on. We create it with 3, each worker calls countDown() when it finishes, and await() returns when the count reaches zero. await(5, SECONDS) gives us the total limit directly and returns a boolean that tells us what happened.

Java
CountDownLatch latch = new CountDownLatch(3);
for (List<Integer> chunk : chunks) {
new Thread(() -> {
try {
process(chunk);
} catch (RuntimeException e) {
errors.add(e); // still our job to keep failures
} finally {
latch.countDown(); // always, or main waits for a worker that died
}
}).start();
}
boolean finished = latch.await(5, TimeUnit.SECONDS); // true, or false on timeout
System.out.println("finished=" + finished); // finished=true

The countDown() call must be in finally. If a worker throws before counting down, the count never reaches zero, and the main thread waits the full 5 seconds and reports a timeout for what was really a failure. The latch only counts; it knows nothing about success or errors.

4Version 3: ExecutorService.invokeAll

invokeAll takes a collection of Callable tasks, runs them on the executor, and waits until all are done or the time runs out. It returns a list of Futures in the same order as the tasks. Tasks that had not finished when the time ran out are cancelled, which interrupts them if they are running.

Java
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
List<Callable<Integer>> tasks = chunks.stream()
.<Callable<Integer>>map(chunk -> () -> process(chunk)) // process returns a count
.toList();
List<Future<Integer>> futures = pool.invokeAll(tasks, 5, TimeUnit.SECONDS);
for (Future<Integer> f : futures) {
try {
System.out.println("processed " + f.get()); // processed 3
} catch (ExecutionException e) {
System.out.println("failed: " + e.getCause()); // the worker's own exception
} catch (CancellationException e) {
System.out.println("timed out"); // did not finish in 5 seconds
}
}
}
Three ways to wait, compared
ApproachOn timeoutIf a worker throws
Thread.join(ms)returns silently; check isAlive()lost to uncaught handler unless collected
CountDownLatch.awaitreturns falselost; count down in finally
invokeAll(tasks, t, unit)unfinished tasks cancelledExecutionException from future.get()

Every possible outcome now has its own clear signal per task: a value, an ExecutionException that wraps the original exception, or a CancellationException for a task that ran out of time. We wrote no extra code to collect errors, and the try-with-resources block (Java 19 and later) closes the executor and waits for its threads.

5What Happens When a Worker Throws

With a raw thread, an exception thrown from run() ends that thread. The JVM passes it to the thread's uncaught exception handler, and the default handler prints the stack trace to System.err. join() then returns normally, as if the thread had succeeded, because join only reports that the thread is no longer alive. So unless we install a handler or catch inside the worker, the main thread cannot tell a failure from a success.

With an executor, the exception is caught by the FutureTask that wraps our Callable and stored in the Future. When we call get(), it is thrown again wrapped in ExecutionException, and getCause() gives us the original. That is the main reason executors and futures are preferred: results, failures and timeouts all come back to the caller through one object, and the pool reuses threads instead of creating them.

6Follow-up questions

What does join() do when the waiting thread is interrupted?

If another thread interrupts the thread that is blocked in join(), join throws InterruptedException and clears the interrupt flag. The thread we were waiting for is not affected at all: it keeps running. So the waiting code must decide what to do, usually restore the flag with Thread.currentThread().interrupt() and stop, possibly interrupting the workers too. The same applies to latch.await() and invokeAll(), which also throw InterruptedException.

Why use System.nanoTime() and not System.currentTimeMillis() for the deadline?

nanoTime is a monotonic clock meant for measuring elapsed time. currentTimeMillis follows the wall clock, which can jump forward or backward when the system time is adjusted, for example by NTP. A deadline based on the wall clock could expire early or last much longer than 5 seconds.

Does invokeAll stop early if the first task fails?

No. invokeAll waits until every task is done, whether it succeeded or failed, or until the timeout. If we need to stop at the first failure and cancel the rest, we need a different tool, such as a CompletionService loop, CompletableFuture with extra code, or structured concurrency.

7Conclusion

In this answer, we waited for three workers with one shared 5-second deadline in three ways. Thread.join(ms) returns silently on timeout, so we check isAlive() and pass only the remaining time to each join. CountDownLatch.await returns false on timeout, and workers must count down in finally. invokeAll returns futures, cancels unfinished tasks, and reports each worker's exception through ExecutionException. Raw threads lose exceptions to the uncaught exception handler unless we collect them, which is why executors and futures are the preferred way to wait for concurrent work.

What to say in the interviewAbout 80 seconds aloud

Open with

I would compute one deadline at the start with System.nanoTime, because the limit is 5 seconds in total, not per thread. With join, I loop over the threads and call join with the remaining milliseconds, skipping zero because join(0) waits forever. join(long) returns silently on timeout, so afterwards I check isAlive on each thread.

Then, if they want more

With a CountDownLatch of 3, each worker calls countDown in a finally block, so a failing worker does not make the main thread wait until the timeout, and the main thread calls await(5, SECONDS), which returns false if the time ran out. With an executor, I call invokeAll with the tasks and a 5-second timeout.

It returns futures in order, cancels any task that has not finished, and for each future get gives the result, throws ExecutionException with the worker's exception as the cause, or throws CancellationException for a timed-out task.

If a worker throws with raw threads, the thread just dies and the exception goes to the uncaught exception handler, which prints it, and join returns as if everything was fine, so I have to collect errors myself. That is why I prefer executors and futures: they carry results and failures back.

And if the waiting thread is interrupted, join throws InterruptedException while the workers keep running.

About this answer

Last updated
12 November 2026
Versions it names
Java 19
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 "Start three worker threads that each process part of a list, and make the main thread...": https://scrivio-interview-library.netlify.app/java/threads/af11419e3c/