Azienda coinvolta
Given a unbounded non-block queue, implement a blocking bounded queue
Anonimo
Assume that the following Queue implementation is given public class Queue { public T dequeue() { //Impl } public void enqueue(T in) { //Impl } public int count() { //Impl} } // Following is the code for a bounded queue // dequeue and enqueue are going to be blocking here, we're not doing a blocking with timeout here // although the intent of the interviewer may have been that public class BoundedBlockingQueue { private Queue queue; private int maxSize; private static final int DEFAULT_SIZE = 10; public BoundedBlockingQueue() { this(DEFAULT_SIZE); } public BoundedBlockingQueue(int maxSize) { this.maxSize = maxSize; queue = new Queue(); } public synchronized T dequeue() { while(true) { if(queue.count() > 0) { notifyAll(); return queue.dequeue(); } else { wait(); } } } public synchronized void enqueue(T in) { while(true) { if(queue.count() < this.maxSize) { // We do not need to notify in other conditions if(queue.count == 1) { notifyAll(); } queue.enqueue(in); return; } else { queue.enqueue(in); return; } } } public int count() { return queue.count(); } }