Quick revision
The short answer
We keep an Object[] items used as a circular buffer with head, tail and count, a final ReentrantLock, and two Conditions created from it, notFull and notEmpty. put takes the lock with lockInterruptibly(), waits with while (count == items.length) notFull.await(), inserts at tail, signals notEmpty, and unlocks in a finally block; take is the mirror image. Two conditions let each operation wake only the kind of thread that can now proceed, and the while loops guard against spurious wakeups. In production we still use ArrayBlockingQueue or LinkedBlockingQueue, because they are thoroughly tested and also offer timeouts, drainTo, fairness and monitoring that a hand-written queue lacks.
What to remember
In this answer, we built a bounded blocking queue from a circular array, a ReentrantLock and two Conditions. put waits on notFull while the queue is full and signals notEmpty after inserting; take does the reverse; both lock with lockInterruptibly, wait in while loops because wakeups can be spurious or stolen, unlock in finally, and propagate InterruptedException. Two conditions mean each signal wakes a thread that can make progress, which is why signal is enough. In production we still use ArrayBlockingQueue or LinkedBlockingQueue, which add timeouts, drainTo, fairness and years of testing.
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.
We keep an Object[] items used as a circular buffer with head, tail and count, a final ReentrantLock, and two Conditions created from it, notFull and notEmpty. put takes the lock with lockInterruptibly(), waits with while (count == items.length) notFull.await(), inserts at tail, signals notEmpty, and unlocks in a finally block; take is the mirror image. Two conditions let each operation wake only the kind of thread that can now proceed, and the while loops guard against spurious wakeups. In production we still use ArrayBlockingQueue or LinkedBlockingQueue, because they are thoroughly tested and also offer timeouts, drainTo, fairness and monitoring that a hand-written queue lacks.
Why this question is asked
A bounded blocking queue is the backbone of producer-consumer designs: thread pools use one to hold waiting tasks, and pipelines use them to apply back-pressure, so a fast producer slows down instead of filling the heap. Writing one by hand is a classic interview task because it exercises everything about locks and conditions in a few dozen lines. In this answer, we will recap ReentrantLock and Condition, write the queue, walk through put and take, explain why two conditions and while loops, look at interruption, and then explain why ArrayBlockingQueue is still what we use in real code.
1A Quick Recap of ReentrantLock and Condition
ReentrantLock is an explicit lock from java.util.concurrent.locks. Like synchronized it gives mutual exclusion, but we call lock() and unlock() ourselves, always unlocking in a finally block, and it offers extras such as lockInterruptibly(), tryLock with a timeout and optional fairness. Reentrant means the thread holding it can lock it again without blocking itself.
A Condition, created with lock.newCondition(), is a named wait set tied to that lock. await() releases the lock and sleeps until another thread calls signal() or signalAll() on the same condition, then reacquires the lock before returning. It is the explicit version of wait and notify, with one important difference: one lock can have several conditions, so threads waiting for different things can wait in different places.
2Writing the Queue
The items live in a fixed array used as a ring: tail is where the next item goes, head is where the next item comes from, and both wrap around to 0 at the end. count tells us whether the ring is full or empty, which head and tail alone cannot distinguish.
7 messages in order. Play them, or step through them one at a time.
await releases the lock, so the consumer can get in and make room.
With capacity 2, two puts fill the ring and a third put waits on notFull. A take then removes the oldest item, signals notFull, and the waiting producer wakes, reacquires the lock, sees count == 1, and inserts. Items come out in the order they went in, because head always trails tail around the ring.
Notice the details that make it correct. Every field is read and written only while holding the lock, so the lock also guarantees that each thread sees the others' writes. unlock() is in finally, so an exception can never leave the lock held. take() clears the slot it read, so the queue does not keep a reference to an object the program no longer needs. And we reject null, because a null item would be indistinguishable from an empty slot in many designs, which is also why the JDK's blocking queues reject it.
3Why Two Conditions and While Loops
With a single condition, or with wait and notifyAll on a monitor, producers and consumers would wait in the same place. A put would have to wake everybody, because it cannot target just a consumer, and the producers it woke would find the queue still full and go back to sleep. Two conditions let a put signal only notEmpty, where consumers wait, and a take signal only notFull, where producers wait. Each signal reaches a thread that can actually make progress.
The while loops are still required. await() may return spuriously, exactly like wait(), and even after a real signal, another thread may get the lock first and take the item or fill the slot before the woken thread runs. So after every wakeup we recheck count, and wait again if the condition is still false.
4Interruption
A thread blocked in put or take may need to be cancelled, for example when an application shuts down its consumers. lockInterruptibly() lets a thread waiting for the lock itself respond to an interrupt, and await() throws InterruptedException when the waiting thread is interrupted. We declare throws InterruptedException and let it propagate, so the caller decides how to stop. If await throws, it has already reacquired the lock, so the finally block's unlock() is still correct.
Swallowing the exception inside the queue would be a bug: a shutdown request would be lost, and the thread would keep waiting forever on a queue nobody fills anymore.
5Why We Still Use ArrayBlockingQueue in Production
Our version is roughly how ArrayBlockingQueue works inside: one lock, two conditions, a circular array. But the JDK class has had years of review, stress testing and production use, and it offers much more: offer(e, timeout, unit) and poll(timeout, unit), which wait only up to a deadline; remainingCapacity(); drainTo(collection), which moves many items under one lock acquisition; a fairness option that hands the lock to waiting threads in arrival order; iterators that stay usable while other threads modify the queue; and full integration with ThreadPoolExecutor and other JDK classes.
LinkedBlockingQueue uses two locks, one for put and one for take, so producers and consumers do not block each other, which often gives higher throughput, and an optional capacity. Writing our own queue is a good way to understand these classes and a good interview exercise, but in production, a hand-written concurrency primitive is code that must be tested under real contention, and the JDK has already done that work.
| Feature | Our queue | ArrayBlockingQueue | LinkedBlockingQueue |
|---|---|---|---|
| Blocking put and take | yes | yes | yes |
| Timed offer and poll | no | yes | yes |
drainTo, remainingCapacity | no | yes | yes |
| Fairness option | no | yes | no |
| Locks | one | one | two: put and take |
| Tested under contention | by us, maybe | years of JDK use | years of JDK use |
6Follow-up questions
Why can signal() instead of signalAll() be safe here?
Because each state change enables exactly one waiting thread, and all threads waiting on a given condition wait for the same thing. One put adds one item, so it can satisfy at most one consumer, and signal on notEmpty wakes one consumer. If that consumer loses the race to another thread, the item is still taken by someone, and the woken thread rechecks and waits again. Using separate conditions is what makes this safe; with a single condition shared by producers and consumers, signal could wake a producer when a consumer was needed, and the system could stall. ArrayBlockingQueue itself uses signal.
Why is count needed when we already have head and tail?
Because head == tail means both full and empty in a circular buffer. When the queue is empty, head and tail point at the same slot, and when it is completely full, tail has wrapped around to head again. count tells the two apart. An alternative is to leave one slot always unused, but count is clearer.
Could you write it with synchronized, wait and notifyAll?
Yes: synchronize put and take on the queue, wait in while loops, and call notifyAll after every change. It is correct, but because there is only one wait set, every change wakes all producers and consumers, and most go back to sleep. Two Conditions avoid those useless wakeups, which is why the JDK uses ReentrantLock here.
7Conclusion
In this answer, we built a bounded blocking queue from a circular array, a ReentrantLock and two Conditions. put waits on notFull while the queue is full and signals notEmpty after inserting; take does the reverse; both lock with lockInterruptibly, wait in while loops because wakeups can be spurious or stolen, unlock in finally, and propagate InterruptedException. Two conditions mean each signal wakes a thread that can make progress, which is why signal is enough. In production we still use ArrayBlockingQueue or LinkedBlockingQueue, which add timeouts, drainTo, fairness and years of testing.
Open with
I would store items in a fixed Object array used as a ring, with head, tail and a count, and protect all of it with one final ReentrantLock.
Then, if they want more
From that lock I create two conditions, notFull and notEmpty. In put, I take the lock with lockInterruptibly, and while count equals the capacity I await on notFull. Then I store the item at tail, advance tail modulo the capacity, increment count, signal notEmpty, and unlock in a finally block.
Take is the mirror image: while count is zero I await on notEmpty, then I read the item at head, null out the slot so the queue does not hold a stale reference, advance head, decrement count, signal notFull, and return the item.
The waits are in while loops because await can wake spuriously, and because another thread can grab the lock first and change the state after I was signalled.
Two conditions matter because producers and consumers wait for different things, so a put wakes only a consumer and a take wakes only a producer, and that is also why plain signal is enough. Both methods throw InterruptedException so a blocked thread can be cancelled. That said, in production I would use ArrayBlockingQueue or LinkedBlockingQueue.
They are built on the same idea, but they are tested under heavy contention and add timed offer and poll, drainTo, remaining capacity, a fairness option, and in LinkedBlockingQueue's case separate locks for producers and consumers.
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 official documentation for the version you use. 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 a bounded blocking queue in Java with put(T) that waits when full and take()...": https://scrivio-interview-library.netlify.app/java/coding-problems/47f87a622d/