Java 关于LinkedBlockingQueue源代码的一些混淆
在LinkedBlockingQueue的源中Java 关于LinkedBlockingQueue源代码的一些混淆,java,java-8,Java,Java 8,在LinkedBlockingQueue的源中 public void put(E e) throws InterruptedException { if (e == null) throw new NullPointerException(); // Note: convention in all put/take/etc is to preset local var // holding count negative to indicate failure unles
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
// Note: convention in all put/take/etc is to preset local var
// holding count negative to indicate failure unless set.
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
try {
/*
* Note that count is used in wait guard even though it is
* not protected by lock. This works because count can
* only decrease at this point (all other puts are shut
* out by lock), and we (or some other waiting put) are
* signalled if it ever changes from capacity. Similarly
* for all other uses of count in other wait guards.
*/
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
// #Question 1
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
1) 如果队列已满,则条件为true
。如果我理解正确,notFull.signal()
调用在LinkedBlockingQueue
的当前实现中实际上是不必要的。因为所有锁和条件都是私有的,所以派生类也不会从调用中受益。所以我想这只是为了确保将来对类的扩展的正确性
2) 获取
takeLock
是必要的,以防止其他线程在发出notEmpty
信号时清空队列。thx…因此我们在jdk源代码中发现了一些额外的代码,我很难相信这一点。你是对的。我希望我没有忽略什么。
private void signalNotEmpty() {
final ReentrantLock takeLock = this.takeLock;
takeLock.lock();
try {
notEmpty.signal();
} finally {
takeLock.unlock();
}
}