Scrivio Interview library
DebuggingFoundations5 min read · updated 12 November 2026

This consumer occasionally throws NoSuchElementException:

Java
synchronized (queue) {
if (queue.isEmpty()) queue.wait();
return queue.remove();
}

Explain.

When the consumer is woken, it must reacquire the queue's lock before wait() returns, and in that gap another consumer may take the item first. wait() can also return spuriously, with no notify at all. Because the code checks the condition with if, the woken thread does not look again and calls remove() on an empty queue, which throws NoSuchElementException. The fix is while (queue.isEmpty()) queue.wait();, and better still, a BlockingQueue, which handles this correctly.

Why this question is asked

This bug is a perfect example of a concurrency failure that tests rarely catch: the code works with one consumer, works most of the time with several, and fails occasionally under load with an exception that seems impossible, since the thread was told an item arrived. Interviewers ask it to see whether we understand what really happens between a notify and the return from wait. In this answer, we will recap the wait protocol, walk through the exact interleaving that causes the exception, cover spurious wakeups, apply the fix, and finish with the BlockingQueue version.

1A Quick Recap of What wait() Promises

A thread calls queue.wait() while holding the queue's monitor. wait() releases the monitor and puts the thread into the queue's wait set. When a producer adds an item and calls notify() or notifyAll(), a waiting thread is moved out of the wait set, but it cannot continue yet: it must reacquire the monitor first, and the producer still holds it until it leaves its synchronized block.

So a notify does not hand the item to the woken thread. It only means something changed, go and look again. Between the notify and the moment our thread actually holds the lock again, any number of other threads may have held it and changed the queue.

2The Interleaving That Causes the Exception

Take two consumers, C1 and C2, and one producer P. C1 finds the queue empty and waits. P adds one item and calls notifyAll(). Before C1 reacquires the lock, C2 arrives, enters the synchronized block, sees that the queue is not empty, skips the if, and takes the item. Now C1 finally gets the lock, wait() returns, and because the check was an if, C1 goes straight to queue.remove() on an empty queue.

Java
synchronized (queue) {
if (queue.isEmpty()) { // C1: true, waits
queue.wait(); // C1 woken by P's notifyAll, but C2 gets the lock first
}
return queue.remove(); // C1: queue is empty again -> NoSuchElementException
}
Step throughAnother consumer takes the item first
Consumer C1queue monitorProducerConsumer C2
isEmpty() true: wait(), release lock
add item, notifyAll()
C1 woken, must reacquire lock
gets lock first: not empty, remove()
reacquires lock; no recheck
remove() on empty queue: exception

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

Being woken only means the state changed; by the time C1 runs, it changed back.

The timing window is small, so the exception is occasional, which matches the report. It shows up more under load, when more consumers compete for the same monitor.

3Spurious Wakeups Make It Worse

Even with a single consumer, the if is wrong. The Java Language Specification and the Object.wait documentation allow a thread to wake up without being notified, interrupted or timed out. These spurious wakeups are rare but real, and they come from how the underlying operating system primitives work.

A consumer woken spuriously finds the queue exactly as empty as before, and with an if it proceeds to remove() anyway. The documentation of wait() itself says that waits should always occur in loops that recheck the condition. So both causes lead to the same rule.

4The Fix: Recheck in a while Loop

Changing if to while means that every time wait() returns, the thread checks the condition again while holding the lock. If another consumer took the item, or the wakeup was spurious, the thread simply waits again. It only proceeds to remove() when it holds the lock and has just seen that the queue is not empty, so remove() cannot fail.

Java
synchronized (queue) {
while (queue.isEmpty()) { // recheck after every wakeup
queue.wait();
}
return queue.remove(); // safe: we hold the lock and just saw an item
}

Notice that the producer side should also call notifyAll() if several consumers or different kinds of threads wait on the same queue; with notify() alone, a wake-up can go to a thread that cannot use it and the signal is lost.

5Better Still: Use a BlockingQueue

java.util.concurrent already has this logic, written and tested. A BlockingQueue such as LinkedBlockingQueue or ArrayBlockingQueue has take(), which waits while the queue is empty and returns an item, and poll(timeout, unit), which waits up to a time limit and returns null if nothing came. Internally they use a lock with conditions and the same while loop.

Java
BlockingQueue<Order> queue = new LinkedBlockingQueue<>(10_000);
// producer
queue.put(order); // waits if the queue is full
// consumer
Order next = queue.take(); // waits until an item exists, never throws NoSuchElementException
Order maybe = queue.poll(500, TimeUnit.MILLISECONDS); // null after 500 ms with no item

The consumer code becomes one line with no synchronized, no wait and no way to get the loop wrong. Bounding the queue, here to 10,000, also gives back-pressure on producers.

6Follow-up questions

Would notify() instead of notifyAll() in the producer avoid the problem?

No. With notify, only one consumer is woken, but C2 can still arrive fresh, without ever waiting, and take the item before C1 reacquires the lock. And spurious wakeups do not depend on notify at all. The while loop is needed either way.

Is this the same as a check-then-act race?

Yes, it is a form of it. The thread checked a condition, then acted later on the assumption it still held. Holding a lock only helps if the check and the act happen in the same continuous hold of the lock; wait() releases the lock in between, so the check must be repeated after it.

How would you test for this bug?

With several consumer threads and a producer adding items one at a time, run in a loop many times, ideally with a stress tool such as jcstress or with random small delays. The failure is probabilistic, so a single test run proves little; reviewing for if around wait() is the more reliable defence, and static analysis tools flag it.

7Conclusion

In this answer, we saw that a thread woken from wait() must reacquire the lock first, and in that gap another consumer can take the item; wait() can also return spuriously. Because the code checked the condition with if, the woken thread did not look again and called remove() on an empty queue, throwing NoSuchElementException. Rechecking in a while loop fixes it, since the thread proceeds only when it holds the lock and has just seen an item, and a BlockingQueue removes the hand-written protocol altogether.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is the if. When a waiting consumer is notified, it does not continue right away: it has to reacquire the queue's monitor before wait returns. In that gap, another consumer can come in, see that the queue is not empty, and take the item.

Then, if they want more

When the first consumer finally gets the lock, it does not check again because of the if, so it calls remove on an empty queue and gets NoSuchElementException. That is why it only happens occasionally, under load with several consumers.

On top of that, wait is allowed to return spuriously, without any notify, and with an if even a single consumer would then remove from an empty queue. The fix is to wait in a loop: while queue.isEmpty, queue.wait.

Then every wakeup rechecks the condition while holding the lock, and the thread only removes when it has just seen an item. The documentation of wait itself says to always wait in a loop.

In practice, though, I would replace this with a BlockingQueue such as LinkedBlockingQueue, where the consumer just calls take, or poll with a timeout, and the library handles the waiting correctly.

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 consumer occasionally throws NoSuchElementException:": https://scrivio-interview-library.netlify.app/java/synchronization/d4b9775435/