I wonder if it is possible to use Semaphore to implement blocking queue?
In the below codes, I use one Semaphore to protect the critical section, and two more Semaphore objects to track the number of empty slots and filled objects.
public class BlockingQueue {
private List<Object> queue = new LinkedList<Object>();
private int limit;
private Semaphore slots; // semaphore for empty slots
private Semaphore objs; // semaphore for filled slots
private Semaphore mutex; // for the critical section
public BlockingQueue(int limit) {
this.limit = limit;
this.slots = new Semaphore(limit); // initial empty slot = capacity
this.objs = new Semaphore(0);
this.mutex = new Semaphore(1);
}
private void enqueue(Object o) throws InterruptedException {
slots.acquire();
mutex.acquire(); // critical section starts
queue.add(o);
mutex.release(); // critical section ends
objs.release();
}
private Object dequeue() throws InterruptedException {
objs.acquire();
mutex.acquire(); // critical section starts
Object o = queue.remove(0);
mutex.release(); // critical section ends
slots.release();
return o;
}
}