I am wondering why wouldn't LinkedBlockingQueue work if we change the underlying data structure to a unthread-safe list like java.util.LinkedList
? I get a NoSuchElementException when I tried it. Doesn't it being guarded by a lock (takeLock) which makes it thread-safe ?
private final List<E> list;
private final ReentrantLock takeLock;
private final ReentrantLock putLock;
private final Condition notFull;
private final Condition notEmpty;
private final AtomicInteger count;
public LinkedBlockingQueue() {
takeLock = new ReentrantLock();
putLock = new ReentrantLock();
notFull = putLock.newCondition();
notEmpty = takeLock.newCondition();
count = new AtomicInteger(0);
list = new LinkedList<E>();
}
public E get() {
E item = null;
int c = -1;
try {
takeLock.lockInterruptibly();
while (count.get() == 0) notEmpty.await();
// original -> item = dequeue();
item = list.remove(); // NoSuchElementException
c = count.getAndDecrement();
}
catch (InterruptedException ie) {}
finally {
takeLock.unlock();
}
if (c == capacity) signalNotFull();
return item;
}
public void put(E e) {
int c = -1;
try {
putLock.lockInterruptibly();
while (count.get() == BOUND_SIZE) notFull.await();
// original -> enqueue(node);
list.add(e);
c = count.getAndIncrement();
}
catch (InterruptedException ie) {}
finally {
putLock.unlock();
}
if (c == 0) signalNotEmpty();
}