Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Implement put and take for a bounded buffer using ReentrantLock with two Conditions, and explain why two conditions are better than one.

The buffer holds a ReentrantLock and two conditions created from it, notFull and notEmpty. put() locks, waits on notFull in a while loop while the buffer is full, inserts, signals notEmpty and unlocks in finally; take() locks, waits on notEmpty in a while loop while it is empty, removes, signals notFull and unlocks in finally. Two conditions are better than one because each signal wakes only a thread waiting for that state, a producer or a consumer, instead of possibly waking the wrong kind of thread, and the while loop protects against spurious wakeups.

Background to this question

The bounded buffer is the classic exercise for Condition objects, and it is the core of real classes such as ArrayBlockingQueue, which is built in almost exactly this way. Writing it by hand shows whether we understand waiting inside a lock, why the wait must be in a loop and why the choice of condition matters. In this answer, we will recap what a Condition is, write the full buffer, walk through put() and take(), explain why the loops are required, and then see the wrong-wakeup problem that two conditions solve.

1A Quick Recap of Conditions

Sometimes a thread holding a lock cannot continue until some state changes, for example a consumer that finds the buffer empty. It cannot just spin while holding the lock, because then the producer could never get in to add an item. A Condition solves this. Calling await() on a condition atomically releases the lock and suspends the thread. Another thread that changes the state calls signal(), which wakes one waiting thread, or signalAll(), which wakes them all. The woken thread reacquires the lock before await() returns.

Conditions are created from a lock with lock.newCondition(), and a thread must hold that lock to call await() or signal(). They play the same role as wait() and notify() on a synchronized monitor, with one important difference: a lock can have as many conditions as we like.

2The Full Bounded Buffer

Here is a fixed-size buffer backed by a circular array. putIndex and takeIndex move around the array, and count tracks how many items are in it.

Java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BoundedBuffer<E> {
private final Object[] items;
private int putIndex, takeIndex, count;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition(); // producers wait here
private final Condition notEmpty = lock.newCondition(); // consumers wait here
public BoundedBuffer(int capacity) { items = new Object[capacity]; }
public void put(E e) throws InterruptedException {
lock.lock();
try {
while (count == items.length) notFull.await(); // full: release lock and wait
items[putIndex] = e;
putIndex = (putIndex + 1) % items.length;
count++;
notEmpty.signal(); // wake one consumer
} finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
public E take() throws InterruptedException {
lock.lock();
try {
while (count == 0) notEmpty.await(); // empty: release lock and wait
E e = (E) items[takeIndex];
items[takeIndex] = null; // let the GC reclaim the item
takeIndex = (takeIndex + 1) % items.length;
count--;
notFull.signal(); // wake one producer
return e;
} finally {
lock.unlock();
}
}
}
// BoundedBuffer<String> b = new BoundedBuffer<>(2);
// b.put("a"); b.put("b"); // count = 2
// b.put("c"); // blocks until a take()
// b.take(); // "a", and wakes the blocked producer

3Walking Through put() and take()

In put(), the thread takes the lock, so it can read count safely. If the buffer is full, it calls notFull.await(), which releases the lock and parks the thread on the notFull condition, so consumers can get in. When it is woken and has the lock again, it checks count again. Once there is room, it stores the item, moves putIndex, increments count and calls notEmpty.signal(), because a consumer might be waiting for exactly this. Finally, unlock() in finally releases the lock on every path, including an InterruptedException from await().

take() is the mirror image. It waits on notEmpty while the buffer is empty, removes the item at takeIndex, clears the slot so the buffer does not hold a reference to an item it has given away, moves takeIndex, decrements count and signals notFull, because a producer might be waiting for space.

Notice that each method signals the condition the other side waits on. Producers wait on notFull and signal notEmpty; consumers wait on notEmpty and signal notFull.

Step throughA producer blocked on a full buffer
ProducerBuffer (lock)Consumer
put(c): buffer full
notFull.await(): releases the lock
take(): gets the lock, removes a
notFull.signal()
producer woken, reacquires the lock
count < capacity: insert c, notEmpty.signal()

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

4Why await() Must Be in a while Loop

There are two reasons the condition must be checked again after every wakeup. First, spurious wakeups: the Condition documentation allows await() to return even when nobody signalled, and implementations may do so. Second, races between waking and running: when a consumer is signalled, it does not run immediately; it must reacquire the lock, and another consumer may get the lock first and take the item it was woken for. By the time it runs, the buffer may be empty again.

With if instead of while, the thread would proceed on an assumption that may no longer be true, and take() would read a null from an empty slot and decrement count below zero. With while, it simply waits again. The rule is the same for wait() on monitors: always wait in a loop that checks the state.

Java
// Wrong: assumes the state after waking
if (count == 0) notEmpty.await();
E e = (E) items[takeIndex]; // may be null: another consumer emptied the buffer first
// Right: re-check after every wakeup
while (count == 0) notEmpty.await();

5Why Two Conditions Are Better Than One

With a synchronized monitor there is only one wait set, so producers waiting for space and consumers waiting for items all wait in the same place, and notify() wakes one arbitrary waiter. Picture a buffer of capacity 1 with two producers and two consumers. Both consumers are waiting because the buffer is empty. Producer 1 puts an item and calls notify(), which wakes consumer 1; producer 2 then finds the buffer full and waits too. Consumer 1 takes the item and calls notify(). The wait set now holds consumer 2 and producer 2, and notify() may pick consumer 2, which finds the buffer empty and goes back to waiting. The signal that producer 2 needed was spent on the wrong kind of thread, and if the remaining threads also end up waiting, nobody is left to wake anyone: the program stalls although there is space and items to add.

The usual workaround with one monitor is notifyAll(), which wakes every waiting thread, producers and consumers, so that the right one is sure to be among them. It is correct but wasteful: every wakeup costs a context switch, and most of the woken threads immediately go back to sleep.

Two conditions remove the problem at its source. Producers only ever wait on notFull and consumers only on notEmpty. So notEmpty.signal() can only wake a consumer, which is exactly the thread that can use the new item, and notFull.signal() can only wake a producer. One signal per state change is enough, and nothing is wasted.

One wait set versus two conditions
DesignWho a signal can wakeCost
synchronized with notify()any waiter, possibly the wrong kindrisk of lost wakeups and stalls
synchronized with notifyAll()every waitercorrect, many useless wakeups
Lock with notFull and notEmptyonly threads waiting for that stateone useful wakeup per change

6Follow-up questions

Why use signal() and not signalAll() here?

Each put() makes room for exactly one consumer and each take() for exactly one producer, so waking one waiter of the right kind is enough. signalAll() would also be correct, but it wakes threads that will just wait again. signalAll() is the right choice when one change can satisfy several waiters, such as a shutdown flag.

What happens if a thread is interrupted while waiting in await()?

await() throws InterruptedException after reacquiring the lock, so the finally block still unlocks correctly. Our put() and take() declare the exception and let it propagate, which tells the caller the operation was cancelled and keeps the interrupt meaningful.

Would you write this class in production code?

Usually not. ArrayBlockingQueue and LinkedBlockingQueue already implement this pattern, carefully tested, with timeouts and draining. Writing it by hand is a good way to understand them, and the same two-condition technique is useful for custom state that the standard queues do not cover.

7Conclusion

In this answer, we built a bounded buffer from a ReentrantLock and two conditions. put() waits on notFull in a while loop, inserts and signals notEmpty; take() waits on notEmpty in a while loop, removes and signals notFull; both unlock in finally. The while loop handles spurious wakeups and races where another thread takes the state first. Two conditions are better than one wait set because each signal can only wake a thread waiting for that state, which avoids wrong wakeups and the waste of notifyAll().

What to say in the interviewAbout 100 seconds aloud

Open with

I would keep an array, a put index, a take index and a count, plus a ReentrantLock and two conditions from it: notFull, where producers wait, and notEmpty, where consumers wait.

Then, if they want more

In put, I lock, then while count equals the capacity I call notFull.await, which releases the lock and parks the thread.

Once there is room I store the item, advance the put index modulo the length, increment count and call notEmpty.signal to wake one consumer, and I unlock in finally. take is the mirror: lock, while count is zero notEmpty.await, read the item, null out the slot so the buffer does not keep a reference, advance the take index, decrement count, call notFull.signal to wake a producer, return the item and unlock in finally.

The await has to be in a while loop, not an if, because await can return spuriously, and because a woken thread must reacquire the lock, and another thread may have taken the item or the space first.

Two conditions are better than one monitor because with a single wait set producers and consumers wait together, so notify can wake the wrong kind of thread and the signal is wasted, which can even stall the system. The usual workaround is notifyAll, which is correct but wakes everyone.

With separate conditions, each signal only wakes a thread that can actually make progress. In real code I would use ArrayBlockingQueue, which is built this way.

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 "Implement put and take for a bounded buffer using ReentrantLock with two Conditions, and...": https://scrivio-interview-library.netlify.app/java/locks/303758080a/