Quick revision
The short answer
The build hangs because latch.await() without a timeout waits forever when the count never reaches zero. That happens when the listener threw before countDown, never received the message at all, or when the latch was created with a higher count than the number of messages actually expected. The fix is to always use await with a timeout and assert its return value, call countDown in finally inside the listener and record failures for the test to check, or use a library such as Awaitility, which gives clear timeouts and failure messages for async assertions.
What to remember
In this answer, we saw that a plain latch.await() hangs forever when countDown is never called, which happens when the listener throws, the message never arrives, or the latch count is higher than the number of messages. Using await with a timeout and asserting its result turns the hang into a fast failure, countDown in finally with recorded failures shows the real cause, and Awaitility lets the test wait for the observable outcome with clear timeouts and failure messages.
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.
The build hangs because latch.await() without a timeout waits forever when the count never reaches zero. That happens when the listener threw before countDown, never received the message at all, or when the latch was created with a higher count than the number of messages actually expected. The fix is to always use await with a timeout and assert its return value, call countDown in finally inside the listener and record failures for the test to check, or use a library such as Awaitility, which gives clear timeouts and failure messages for async assertions.
Why this question is asked
A test that fails is annoying; a test that hangs is much worse, because it blocks the whole pipeline, gives no error message, and usually only happens sometimes. Message-driven tests with a latch are a frequent cause. Interviewers ask this to see whether we can reason about the possible causes and make the test fail fast with a useful message. In this answer, we will look at the typical test, go through the reasons the latch never opens, then make the test robust step by step, and finally rewrite it with Awaitility.
1The Typical Test
The test sends a message, and a listener in the application, for example a Kafka or JMS listener, processes it on its own thread. To know when processing is done, the listener counts down a latch that the test waits on.
Notice that the only way out of await() is the count reaching zero. Any path in which countDown is not called leaves the test thread blocked, and the CI job waits until its own global timeout kills it, often an hour later.
2Why the Latch Never Opens
There are three common causes. First, the listener threw. If service.handle throws, countDown is skipped. The exception goes to the listener container's error handler, which may log it at a level the CI output does not show, and may retry the message several times, each time failing the same way.
Second, the listener never received the message. In integration tests this is common: the consumer had not finished joining its group or being assigned partitions when the test sent the message, it subscribed with auto.offset.reset=latest and so skipped a message sent just before, the topic name differs by a typo or a profile, or the message failed to deserialize and went to an error handler. Timing differences between a laptop and a busy CI machine explain why it fails only sometimes.
Third, the count is too high. If the latch was created with new CountDownLatch(3) but the test sends only two messages, or one of three messages is filtered out by the listener, the count stops at 1 forever. This is easy to introduce when a test is changed and the latch count is not.
- Message reached the listener?YesContinueNoConsumer not ready, wrong topic, deserialization error
- Listener finished without throwing?YesContinueNocountDown skipped: exception in handle
- Count matches messages expected?YesLatch opensNoCount stops above zero
- Plain await() with no timeouttest thread blocked, CI hangs
4 steps in order. Play them, or step through them one at a time.
3Always Await With a Timeout and Assert the Result
The first fix turns a hang into a failure. The timed await returns false when the time runs out, and we assert on that value with a clear message.
Notice that we include getCount() in the message. A remaining count tells us at a glance whether no messages were processed or just one was missing. Even before we find the real cause, the build now fails in 10 seconds instead of hanging.
4CountDown in finally, and Record Failures
Next, the listener must count down whatever happens, and it must leave evidence when it fails. We put countDown in a finally block and store any exception where the test can read it.
So when the listener throws, the test fails immediately with the real exception instead of a timeout. If the message never arrives at all, the timed await still catches it. Notice the volatile field: the test replaces the latch from another thread, and the listener thread must see the new one. Better still is to avoid putting test hooks into production code at all, which is what Awaitility helps with.
5Use Awaitility for Async Assertions
Awaitility is a small testing library that repeatedly checks a condition until it holds or a timeout passes. Instead of signalling from the listener, the test simply waits for the observable outcome, for example the order appearing in the repository.
Notice that the listener no longer needs a latch, and the failure message shows both the timeout and the last failed assertion. We still need to deal with the second cause, the message not being received: wait for the consumer's partition assignment before sending, or use auto.offset.reset=earliest in tests, which the test infrastructure for Kafka usually offers a helper for; check your Spring Kafka version.
6Follow-up questions
What timeout should a test use?
Long enough for a slow CI machine, short enough that a failure is quick: often 5 to 30 seconds for integration tests. Set it from the expected processing time with a generous margin, and keep it in one constant so all tests use the same value and it is easy to adjust.
Should every test also have a global timeout?
Yes, as a safety net. JUnit 5 and later offer @Timeout on a test or class, and a default timeout can be configured for the whole suite. It turns any remaining hang into a test failure with a thread dump option, instead of a stuck build.
Why does the problem appear only sometimes?
Because the causes are timing-dependent: a consumer that joins its group a little later on a busy CI machine misses a message sent too early, or a retry policy makes processing slower than the test expects. Tests that pass on a fast laptop can fail under CI load, which is why fixed sleeps are a poor fix and polling with a timeout is better.
7Conclusion
In this answer, we saw that a plain latch.await() hangs forever when countDown is never called, which happens when the listener throws, the message never arrives, or the latch count is higher than the number of messages. Using await with a timeout and asserting its result turns the hang into a fast failure, countDown in finally with recorded failures shows the real cause, and Awaitility lets the test wait for the observable outcome with clear timeouts and failure messages.
Open with
The test hangs because await without a timeout only returns when the count reaches zero, and in some runs countDown is never called. I can see three likely causes.
Then, if they want more
One, the listener threw before countDown, for example the service failed, so countDown was skipped and the exception went to the container's error handler, maybe with retries.
Two, the listener never got the message, which is common in integration tests: the consumer had not been assigned partitions yet when the test sent, it started at the latest offset and skipped it, the topic name was wrong in that profile, or deserialization failed. Those depend on timing, which explains why it only happens sometimes on CI.
Three, the latch count is higher than the number of messages the test really produces. To make it robust, I would first always use await with a timeout and assert that it returned true, with getCount in the message, so the build fails in seconds instead of hanging.
Then I would move countDown into a finally block in the listener and record any exception in a concurrent queue that the test asserts is empty, so we see the real error.
Even better, I would use Awaitility to poll for the observable result, like the row in the repository, with a clear timeout, and make sure the consumer is ready before sending. I would also put a global JUnit timeout on the suite as a safety net.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- JUnit 5
- 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 "An integration test that waits on latch.await() sometimes hangs the whole CI build. The...": https://scrivio-interview-library.netlify.app/java/synchronizers/ea086ecc8a/