I am trying to understand Java's synchronized keyword, wait(), and notify() by implementing a blocking queue class. One of the blocking queue implementation is described by this article. However I wonder if it is possible to use two objects serving as lock to implement blocking queue? Is the below code correct?
public class BlockingQueue {
private List<Object> queue = new LinkedList<Object>();
private int limit;
private Object slots = new Object();
private Object objs = new Object();
public BlockingQueue(int limit) {
this.limit = limit;
}
private synchronized void enqueue(Object o)
throws InterruptedException {
if (queue.size() == limit)
slots.wait();
objs.notify();
queue.add(o);
}
private synchronized Object dequeue()
throws InterruptedException {
if (queue.size() == 0)
objs.wait();
slots.notify();
return queue.remove(0);
}
}