Linkedin Interview Question
Software Engineer / DevelopersCountry: United States
I think the above code is incorrect. If a reader blocks when the queue count was 0, then a writer puts something in the queue, the reader should be unblocked. The code above unblocks only when the queue fills to limit.
Calling "notifyAll()" on every Write() could be inefficient if the implementation is not tracking the number of blocked Readers(). I mean you don't want a system call on every queue Write().
[Note everything above is also true for Writers blocked on Limit, and readers need to unblock them]
public class MyBlockingQueue<T> {
private Queue<T> queue;
private AtomicInteger limit = new AtomicInteger(10);
private Lock put_lock = new ReentrantLock();
private Lock take_lock = new ReentrantLock();
public MyBlockingQueue(AtomicInteger limit){
queue = new LinkedList<T>();
this.limit = limit;
}
public boolean put(T item) throws InterruptedException{
put_lock.lockInterruptibly();
try{
while(queue.size() == limit.get()){
put_lock.newCondition().await();
}
put_lock.newCondition().signal();
queue.add(item);
}finally{
put_lock.unlock();
}
return true;
}
public T take() throws InterruptedException{
take_lock.lockInterruptibly();
try{
while(queue.size() == 0){
take_lock.newCondition().await();
}
take_lock.newCondition().signal();
return queue.poll();
}finally {
take_lock.unlock();
}
}
}
- chandershivdasani September 15, 2012