Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write code that starts 5 worker tasks and waits until all have finished their setup step before the main thread continues, with a timeout of 30 seconds. Explain what happens if a worker throws before counting down.

We create CountDownLatch ready = new CountDownLatch(5), each worker does its setup and calls ready.countDown() in a finally block, and the main thread calls ready.await(30, TimeUnit.SECONDS) and handles a false result as a timeout. If a worker throws before counting down and countDown is not in finally, the count never reaches zero, so await waits until the timeout, or forever without one. A latch is one-shot and cannot be reset, and countDown happens-before a successful return from await, so the setup results are visible to the main thread.

Why this question is asked

Waiting for several threads to reach a point before continuing is a very common need: warming caches before accepting traffic, opening connections before a load test starts, or making sure consumers are subscribed before a test sends messages. CountDownLatch is the classic tool for it, and interviewers use this question to check that we write it safely, with a timeout and with failures in mind. In this answer, we will recap how a latch works, write the code, break it with a failing worker, fix it with finally and error recording, and look at the visibility guarantee and the one-shot nature of the latch.

1A Quick Recap of CountDownLatch

A CountDownLatch is a counter that threads can wait on. We create it with a starting count, here 5. Any thread can call countDown(), which lowers the count by one. Threads that call await() block until the count reaches zero, and from then on await() returns immediately for everyone. The count never goes below zero and never goes back up, so a latch opens only once.

The timed form await(timeout, unit) waits at most that long. It returns true if the count reached zero and false if the time ran out, which is how we tell success from a timeout.

2Writing the Code

Each worker does its setup, counts down, and then carries on with its main work. The main thread waits for all five setups, with a 30-second limit.

Java
ExecutorService pool = Executors.newFixedThreadPool(5);
CountDownLatch ready = new CountDownLatch(5);
Map<Integer, Connection> connections = new ConcurrentHashMap<>();
for (int i = 0; i < 5; i++) {
int id = i;
pool.submit(() -> {
try {
connections.put(id, openConnection(id)); // the setup step
} finally {
ready.countDown(); // always, even if setup throws
}
doMainWork(id); // continues after setup
return null;
});
}
if (!ready.await(30, TimeUnit.SECONDS)) { // true when all 5 counted down
throw new IllegalStateException("workers not ready after 30 s, count = " + ready.getCount());
}
System.out.println("ready: " + connections.size()); // ready: 5
Step throughFive workers open the latch
Main threadLatch (count 5)Workers 1..5
await(30 s)
setup: open connections
countDown() x5 in finally
count reaches 0, latch opens
await returns true
continue with main work

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

Each worker counts down once; the main thread continues when the count is zero.

Notice that the main thread checks the return value of await. Ignoring it would make a timeout look exactly like success, and the program would continue with workers that are not ready. Notice also that the task is a Callable, because it ends with return null, so it may throw; that matters for the next section.

3What Happens When a Worker Throws

Suppose worker 3's openConnection throws, and countDown was written after the setup instead of in finally.

Java
pool.submit(() -> {
connections.put(id, openConnection(id)); // worker 3 throws SQLException here
ready.countDown(); // never reached for worker 3
doMainWork(id);
return null;
});
ready.await(30, TimeUnit.SECONDS); // false after 30 s, count = 1
ready.await(); // without a timeout: waits forever

The count stops at 1, because only four workers counted down, and nothing will ever lower it further. With the timed await, the main thread waits the full 30 seconds and then gets false. With a plain await(), it waits forever, and the program hangs with no error in the logs, because the exception was stored in the Future returned by submit, which nobody looked at.

4Fix: countDown in finally, and Record the Failure

Putting countDown in a finally block guarantees it runs whether the setup succeeds or throws, so the latch always opens and the main thread is never stuck. But now a failed setup also opens the latch, so the main thread needs to know whether setups actually succeeded. We record failures in a shared, thread-safe place and check it after await.

Java
Queue<Throwable> failures = new ConcurrentLinkedQueue<>();
pool.submit(() -> {
try {
connections.put(id, openConnection(id));
} catch (Exception e) {
failures.add(e); // remember why this worker failed
throw e;
} finally {
ready.countDown();
}
doMainWork(id);
return null;
});
if (!ready.await(30, TimeUnit.SECONDS)) throw new IllegalStateException("setup timed out");
if (!failures.isEmpty()) throw new IllegalStateException("setup failed", failures.peek());
// IllegalStateException: setup failed Caused by: SQLException: connection refused

So the main thread now ends in one of three clear states: all five ready, a timeout, or a reported failure with its cause, instead of a silent hang.

5Visibility and the One-Shot Rule

The latch also gives a memory guarantee. Actions a thread performs before calling countDown() happen-before actions that follow a successful return from await() in another thread. In plain words, once await returns true, the main thread is guaranteed to see everything the workers wrote during setup, such as the connections they stored, even without other synchronization. Here we used a ConcurrentHashMap anyway, but the guarantee would also cover plain fields set by the workers before counting down.

A latch cannot be reset. Once the count is zero it stays open, and there is no method to set it back to 5. If we need the same kind of gate again, for example once per test or once per batch, we create a new CountDownLatch, or use a CyclicBarrier or Phaser, which are designed to be reused across rounds.

6Follow-up questions

Why not call countDown at the very end of the worker task?

Because the main thread only needs the setup to be done, not the main work. Counting down right after setup lets the main thread continue as soon as all workers are ready, while the workers keep running. It also keeps the latch's meaning precise: ready means setup finished.

What if a worker calls countDown twice by mistake?

The count drops twice, so the latch may open before every worker is ready, and the main thread proceeds early. countDown has no notion of who is calling. Keep exactly one countDown per worker, which the single finally block guarantees.

Could CompletableFuture.allOf replace the latch here?

Only if setup were a separate task whose completion we wait for. Here the workers continue running after setup, so the event we wait for is not the end of a task. That is exactly the case where a latch fits better than allOf or invokeAll.

7Conclusion

In this answer, we created a CountDownLatch with a count of 5, had each worker call countDown in a finally block after its setup, and had the main thread call await(30, TimeUnit.SECONDS) and treat false as a timeout. We saw that a worker throwing before an unprotected countDown leaves the count above zero, so await waits until the timeout or forever, and that recording failures lets the main thread tell a failed setup from success. Finally, countDown happens-before a successful await, so setup results are visible, and a latch is one-shot and cannot be reset.

What to say in the interviewAbout 80 seconds aloud

Open with

I would create a CountDownLatch with a count of five and share it with the five workers. Each worker does its setup inside a try block and calls ready.countDown() in the finally block, then carries on with its main work.

Then, if they want more

The main thread calls ready.await(30, TimeUnit.SECONDS), and because that returns a boolean, I check it: false means the timeout passed before all five counted down, so I fail with a clear message including getCount. The finally matters because of the failure case.

If countDown were just after the setup and a worker threw, that worker would never count down, the count would stay at one, and await would wait the full thirty seconds, or forever without a timeout, with no error in the logs because the exception sits in an unobserved Future.

With finally, the latch always opens, but then a failed setup looks like success, so I also record exceptions in a concurrent queue and check it after await.

Two more points: the latch gives a happens-before guarantee, so whatever a worker wrote before countDown is visible to the main thread after await returns true; and a latch is one-shot, it cannot be reset, so for repeated rounds I would create a new one or use a CyclicBarrier or Phaser.

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 "Write code that starts 5 worker tasks and waits until all have finished their setup step...": https://scrivio-interview-library.netlify.app/java/synchronizers/08026c7e18/