Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

What is a guarded block, and why is it better than polling a flag in a loop with sleep?

A guarded block is a piece of code that waits, without running, until some condition becomes true: inside synchronized (lock) it loops on while (!condition) lock.wait(), and the thread that makes the condition true changes it under the same lock and calls notifyAll(). It beats polling a flag with sleep because the waiting thread uses no CPU at all and wakes up as soon as it is notified, instead of either burning CPU or adding up to one sleep interval of delay.

Why this question is asked

Almost every concurrent program has a moment where one thread must wait for another: a consumer waits for data, a worker waits for a start signal, a request waits for a connection to become free. How we write that wait decides whether the program wastes CPU, reacts slowly, or hangs. Interviewers ask about guarded blocks because most of java.util.concurrent is built on them. In this answer, we will look at the polling approach and its costs, build a guarded block step by step, see why the condition is rechecked in a loop, and then see how the library classes we normally use implement the same idea.

1The Problem: Waiting for Another Thread

Suppose one thread loads a set of prices from a remote service, and a second thread must not start serving requests until the prices are there. The simplest idea is a shared flag: the loader sets loaded = true when it finishes, and the other thread keeps checking the flag until it sees true. Checking repeatedly is called polling.

Java
volatile boolean loaded = false;
// Busy polling: one core runs at 100% until the flag flips
while (!loaded) { }
// Sleep polling: cheap on CPU, but reacts up to 100 ms late
while (!loaded) {
Thread.sleep(100);
}

The tight loop keeps one CPU core fully busy doing nothing useful. With ten such waiters on eight cores, waiting starves the real work. The sleeping loop fixes the CPU problem but adds latency: if the flag flips just after the check, the waiter notices up to 100 ms later. Shorter sleeps mean less latency but more wasted wakeups, so we are forced to trade one cost for the other. The flag must also be volatile, or the waiter may never see the change.

2Building a Guarded Block

A guarded block removes that trade-off. Instead of checking on a timer, the waiting thread asks the JVM to put it to sleep until another thread tells it that something has changed. Java gives every object a monitor, a lock plus a waiting room, and the methods wait(), notify() and notifyAll() on Object use that waiting room.

The pattern has two halves. The waiting side takes the lock, checks the condition, and calls wait() while the condition is false. The changing side takes the same lock, changes the state, and calls notifyAll().

Java
class PriceTable {
private final Object lock = new Object();
private boolean loaded = false; // guarded by lock
void awaitLoaded() throws InterruptedException {
synchronized (lock) {
while (!loaded) {
lock.wait(); // releases lock, sleeps, reacquires lock on wakeup
}
// here loaded is true, and we still hold the lock
}
}
void markLoaded() {
synchronized (lock) {
loaded = true;
lock.notifyAll(); // wakes every thread waiting on lock
}
}
}
Step throughA guarded block over time
WaiterLock monitorLoader
lock, see loaded == false
wait(): release lock and sleep
lock, set loaded = true
notifyAll(), then unlock
wake up, reacquire lock
recheck: loaded == true, continue

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

The waiter uses no CPU between its wait() and the loader's notifyAll().

The key detail is what wait() does with the lock. It releases the lock and parks the thread in one atomic step, so the changing thread can enter its synchronized block. When the waiter is woken, it must take the lock back before wait() returns. That is why it is safe to read loaded right after: we hold the lock again, and the loader wrote the flag under that same lock.

The flag does not need volatile here. The reason is that both sides access it only while holding the same lock, and the release of a lock happens-before the next acquisition of it, so the write is guaranteed to be visible. Calling wait() or notifyAll() without holding the lock is an error: the JVM throws IllegalMonitorStateException.

3Why the Condition Is Rechecked in a While Loop

A beginner often writes if (!loaded) lock.wait() instead of a while loop. It looks equivalent, but it is not, and the difference is the most common bug in hand-written guarded blocks.

First, the JVM is allowed to wake a waiting thread for no reason at all. This is called a spurious wakeup, and the Java documentation explicitly says that wait() should always be called in a loop because of it. Second, notifyAll() wakes every waiter, but only one of them gets the lock first. By the time a later thread gets the lock, the first one may have changed the state again. For example, with a queue of one item and three waiting consumers, notifyAll() wakes all three, the first takes the item, and the other two must go back to waiting. Third, a single lock is often used for several conditions, so a wakeup may concern a different condition entirely. A while loop handles all three cases the same way: the thread checks again and goes back to waiting.

4Why notifyAll() Rather Than notify()

notify() wakes just one waiting thread, chosen by the JVM. It is tempting because it causes fewer wakeups, but it is only safe when every waiter waits for the same condition and any one of them can make progress. If the chosen thread is waiting for a different condition, it goes back to sleep and the notification is lost, while a thread that could have proceeded keeps sleeping. That is the classic lost wakeup, and it produces stalls that are very hard to reproduce. notifyAll() costs a few extra wakeups, but combined with the while loop it is always correct, so it is the safe default.

5How Waiting and Polling Compare

It helps to put the three approaches side by side, using a waiter that waits for about two seconds.

Three ways to wait for a flag
ApproachCPU while waitingDelay after the change
Busy loop on a volatile flagOne core at 100% for 2 sAlmost none
Sleep 100 ms between checksAbout 20 wakeups, near zeroUp to 100 ms
Guarded block with wait/notifyAllZero, thread is parkedMicroseconds

The guarded block wins on both axes at once: the parked thread costs nothing and wakes on the notification itself.

6The Same Idea in java.util.concurrent

In application code we rarely write wait() and notifyAll() ourselves, because the standard library already packages guarded blocks into well-tested classes. CountDownLatch lets threads wait until a count reaches zero. BlockingQueue lets consumers wait until an item is available and producers wait until there is room. Semaphore lets threads wait until a permit is free. Internally they use locks and condition queues, Lock and Condition objects that are the flexible cousin of synchronized and wait, but the logic is exactly the guarded block: check a condition, park while it is false, and wake when another thread changes it.

Java
CountDownLatch loaded = new CountDownLatch(1);
// waiting thread
loaded.await(); // parks until the count is 0
// loader thread
loaded.countDown(); // count 1 -> 0, wakes every waiter
boolean ok = loaded.await(5, TimeUnit.SECONDS); // true: already open, returns at once

The latch version is shorter, cannot forget the while loop or the lock, and adds features such as a timeout. That is why, in real code, we reach for these classes first and keep the raw pattern for understanding and for the rare case nothing in the library fits.

7Follow-up questions

What is a spurious wakeup?

It is a return from wait() that no notify() or notifyAll() caused. The Java specification allows it because some operating systems implement thread parking in a way that can wake a thread early, and forbidding it would make the JVM slower. It is rare, but code must be correct when it happens, which is the main reason wait() always sits inside a while loop that rechecks the condition.

Why must wait() be called while holding the lock?

Because the check of the condition and the decision to sleep must be atomic. Without the lock, the other thread could change the condition and call notifyAll() between our check and our wait(), and we would sleep forever after missing the notification. Java enforces this by throwing IllegalMonitorStateException when wait or notify is called by a thread that does not own the monitor.

8Conclusion

In this answer, we saw that polling a flag forces a choice between burning CPU and reacting late, while a guarded block lets the waiting thread park with no CPU cost and wake as soon as the state changes. The waiter checks the condition in a while loop under a lock and calls wait(), the changer modifies the state under the same lock and calls notifyAll(), and the loop handles spurious wakeups and competing waiters. Library classes such as CountDownLatch and BlockingQueue implement the same idea for us, and they are what we should normally use.

What to say in the interviewAbout 80 seconds aloud

Open with

A guarded block is code that waits until a condition is true without consuming CPU. The waiting thread takes a lock, and while the condition is false it calls wait on that lock, which releases the lock and parks the thread.

Then, if they want more

The thread that changes the state takes the same lock, updates the state, and calls notifyAll, so the waiters wake up, reacquire the lock and check again.

It is better than polling with sleep because polling forces a trade-off: a tight loop burns a whole core, and a sleeping loop adds up to one sleep interval of latency and still wakes up pointlessly. A guarded block costs nothing while waiting and reacts almost immediately. The two details people get wrong are the while loop and the lock.

The loop is needed because of spurious wakeups and because, after notifyAll, another thread may have consumed the state first. The lock is needed so the check and the wait are atomic; otherwise a notification can be lost, and Java throws IllegalMonitorStateException anyway if we call wait without it. In practice I rarely write this by hand.

CountDownLatch, BlockingQueue and Semaphore are guarded blocks packaged and tested, with timeouts and interruption handled, so I use them and keep the raw pattern for understanding.

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 "What is a guarded block, and why is it better than polling a flag in a loop with sleep?": https://scrivio-interview-library.netlify.app/java/synchronization/72b0d35eef/