Domanda di colloquio di LinkedIn

Given a unbounded non-block queue, implement a blocking bounded queue

Risposte di colloquio

Anonimo

12 mar 2011

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(); } }

1

Anonimo

19 feb 2012

From what I understood, the enqueue method will queue all the elements . Shouldn't we wait when the process if the queue is full , i.e., if (queue.count > this.maxSize) { wait() }

1