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 BlockingQueues 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 useReentrantLockinstead ofsynchronized.It has the same semantics as
syncrhonized, but provides some improvements. In particular, it can have several conditions other threads canwaiton: