Quick revision
The short answer
A bounded buffer keeps its items and a count, and both put and take are synchronized on the buffer. put waits in a while (count == capacity) loop, inserts, and calls notifyAll(); take waits in a while (count == 0) loop, removes, and calls notifyAll(). Each rule has a reason: wait and notify must be called while holding the monitor or they throw IllegalMonitorStateException, the condition is checked in a while loop because of spurious wakeups and because another thread may change the state first, notifyAll is needed because producers and consumers wait on the same monitor for different conditions, and wait releases the monitor while waiting and reacquires it before returning.
What to remember
In this answer, we wrote a bounded buffer with synchronized put and take, each waiting in a while loop for its condition, changing the state, and calling notifyAll. We saw why each rule is needed: wait and notify require the monitor to prevent lost wake-ups, the while loop handles spurious wakeups and threads that get there first, notifyAll is needed because producers and consumers share one wait set, and wait releases the monitor while waiting and reacquires it before returning, so the recheck happens under the lock.
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.
A bounded buffer keeps its items and a count, and both put and take are synchronized on the buffer. put waits in a while (count == capacity) loop, inserts, and calls notifyAll(); take waits in a while (count == 0) loop, removes, and calls notifyAll(). Each rule has a reason: wait and notify must be called while holding the monitor or they throw IllegalMonitorStateException, the condition is checked in a while loop because of spurious wakeups and because another thread may change the state first, notifyAll is needed because producers and consumers wait on the same monitor for different conditions, and wait releases the monitor while waiting and reacquires it before returning.
Background to this question
The bounded buffer is the classic exercise for wait and notify, because it needs both directions of waiting: producers wait when the buffer is full and consumers wait when it is empty. In real code we would use an ArrayBlockingQueue, but writing one by hand shows whether we understand every rule of the monitor protocol, and each rule exists because breaking it causes a specific bug. In this answer, we will recap what wait and notify do, write the buffer, and then go through the code rule by rule, showing what breaks without each one.
1A Quick Recap of wait and notify
Every object's monitor has, besides the lock, a wait set: a list of threads that are waiting for some condition about that object to change. A thread that holds the monitor and finds it cannot continue, for example because the buffer is full, calls wait(). That puts the thread into the wait set and releases the monitor so other threads can enter and change the state.
Another thread that changes the state calls notify(), which moves one waiting thread out of the wait set, or notifyAll(), which moves all of them. A woken thread does not run immediately: it first has to reacquire the monitor, competing with every other thread that wants it, and only then does wait() return.
2The Bounded Buffer
We store items in a circular array with a head index for taking, a tail index for putting, and a count of items. Everything is guarded by the buffer's own monitor, so both methods are synchronized.
6 messages in order. Play them, or step through them one at a time.
The producer only continues after reacquiring the lock and rechecking the condition.
Notice that the condition check, the wait and the state change are all inside the same synchronized method. That is what makes the check-then-act safe: no other thread can change count between our check and our insert.
3Rule 1: Call wait and notify Only While Holding the Monitor
wait(), notify() and notifyAll() must be called by a thread that owns the object's monitor, which in our code means inside the synchronized methods. Called anywhere else, they throw IllegalMonitorStateException.
The reason is the lost wake-up problem. If a consumer could check count == 0 without the lock and then call wait(), a producer could slip in between, add an item and notify, before the consumer had started waiting. The notification would go to nobody, and the consumer would then wait forever for an item that is already there. Requiring the lock for both the check and the wait makes them one atomic step from the producer's point of view.
4Rule 2: Wait in a while Loop, Never an if
When wait() returns, the condition we waited for may not be true. There are two reasons. First, spurious wakeups: the Java specification allows wait() to return without any notify, and some platforms really do this. Second, and more common, another thread may get there first. notifyAll wakes, say, three consumers for one new item; one of them reacquires the lock first and takes the item, and when the second one finally gets the lock, the buffer is empty again.
With while, each woken thread rechecks the condition after reacquiring the lock and goes back to waiting if it is still false. With if, it would continue and, in take(), read an empty slot, return null and make count negative, corrupting the buffer.
5Rule 3: Use notifyAll Because Two Kinds of Threads Share One Wait Set
Producers wait for not full and consumers wait for not empty, but there is only one wait set per monitor, so both kinds wait in it together. notify() wakes one arbitrary thread. If a consumer takes an item and its notify happens to wake another consumer instead of a waiting producer, that consumer finds the buffer empty and waits again, and the producer that could have used the free space is never told. The signal is lost and the program can stall with work available.
notifyAll() wakes everyone, so the thread that can make progress is always among them, and the while loops send the others back to waiting. It costs some unnecessary wake-ups, but it is always correct here.
6Rule 4: Understand That wait Releases and Reacquires the Monitor
wait() is the only way to give up a monitor while still inside a synchronized method. It releases the lock completely, even if the thread had entered it several times, so producers and consumers can get in and change the state. Before wait() returns, the thread reacquires the monitor and its previous hold count. So after wait() we are once again holding the lock, which is why we can safely recheck the condition and change the state.
This also explains InterruptedException in the signatures. If another thread interrupts a waiting thread, wait() reacquires the lock and then throws InterruptedException. We pass it up, so callers can stop cleanly.
7Follow-up questions
Why not use separate locks or conditions for producers and consumers?
With an intrinsic monitor we only get one wait set. A ReentrantLock with two Condition objects, notFull and notEmpty, lets producers and consumers wait separately, so put can signal exactly one consumer with notEmpty.signal(). That is how ArrayBlockingQueue is written, and it avoids waking the wrong kind of thread.
What would you use in production code?
java.util.concurrent.ArrayBlockingQueue or LinkedBlockingQueue, with put and take, or offer and poll with timeouts. They are tested, handle interruption and fairness options, and make the intent obvious. Writing a buffer by hand is useful for understanding, not for shipping.
Why set items[head] to null after taking?
Otherwise the array keeps a reference to an object we have already handed out, which prevents garbage collection until that slot is overwritten. In a large buffer of large objects this is a real memory leak.
8Conclusion
In this answer, we wrote a bounded buffer with synchronized put and take, each waiting in a while loop for its condition, changing the state, and calling notifyAll. We saw why each rule is needed: wait and notify require the monitor to prevent lost wake-ups, the while loop handles spurious wakeups and threads that get there first, notifyAll is needed because producers and consumers share one wait set, and wait releases the monitor while waiting and reacquires it before returning, so the recheck happens under the lock.
Open with
I would keep a circular array with head, tail and count, and make both put and take synchronized on the buffer. In put, while count equals the capacity, I call wait; then I insert at tail, advance it, increment count and call notifyAll.
Then, if they want more
In take, while count is zero, I wait; then I remove from head, null out the slot, decrement count, call notifyAll and return the item. Each rule has a reason. wait and notify must be called while holding the monitor, otherwise they throw IllegalMonitorStateException; that requirement prevents lost wake-ups, where a producer notifies between a consumer's check and its wait.
The condition is checked in a while loop, not an if, because wait can wake up spuriously and, more often, because another thread can reacquire the lock first and take the item, so the woken thread must recheck.
I use notifyAll because producers and consumers wait in the same wait set for different conditions, and notify could wake a thread of the wrong kind, losing the signal. And wait releases the monitor while waiting, so others can change the state, and reacquires it before returning, so the recheck and update are safe.
In production I would just use an ArrayBlockingQueue, which uses one lock with two conditions.
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.
- 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 "Write a bounded buffer with synchronized, wait and notifyAll supporting put and take...": https://scrivio-interview-library.netlify.app/java/synchronization/0d91cf22db/