I am writing a BlockingQueue and am wondering how other implementations solve this problem:
If I only have one monitor (the queue object) and let producers and consumers wait
, I will have to ensure that notifyAll
instead of notify
is called, otherwise a producer might only signal another waiting producer to continue even if the queue is full. Making the consumer wait even though stuff is available. On the other hand calling notifyAll
doesn't seem to be a scalable solution for many threads and processors.
Do BlockingQueue
s use two monitors? One were the producers wait and one were the consumers wait? Then I would have to synchronize the the queue and the relavant monitor in a encapsulated manner. Is that the way to go?
I'm not sure how it's done in BlockingQueue
, but one possible solution is to use ReentrantLock
instead of synchronized
.
It has the same semantics as syncrhonized
, but provides some improvements. In particular, it can have several conditions other threads can wait
on:
public class MyBlockingQueue<E> {
private Lock lock = new ReentrantLock();
private Condition notEmpty = lock.newCondition();
private Condition notFull = lock.newCondition();
public void put(E e) {
lock.lock();
try {
while (isFull()) notFull.await();
boolean wasEmpty = isEmpty();
...
if (wasEmpty) notEmpty.signal();
} finally {
lock.unlock();
}
}
public E take() {
lock.lock();
try {
while (isEmpty()) notEmpty.await();
boolean wasFull = isFull();
...
if (wasFull) notFull.signal();
...
} finally {
lock.unlock();
}
}
...
}