我正在阅读 Java LinkedBlockingQueue
源代码,我有两个关于 put
operation的问题.
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();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
我不明白:
- 它检查
c + 1 < capacity
,当它发出notFull.signal()
时。为什么不使用c < capacity
? - 为什么会发出
signalNotEmpty
当c == 0
在函数结束时?
此外,我也不明白为什么头/尾需要是 transient
?
最佳答案
您的两个问题的答案:
- 在
c + 1 < capacity
之前检查一下,有一个电话c = count.getAndIncrement();
。由于计数在检索并分配给c
之后递增。 ,c
之间存在 1 差异和实际计数,因此+ 1
在支票上。 - 只有当队列从空转变为非空时才需要发送非空信号。仅当第一个元素添加到空(0 个元素)队列时才会出现这种情况。至于
c
此时是0而不是1,请引用第一个问题的答案。
关于head
和tail
是transient
:它们不需要在对象序列化时持久化,因为它们是在对象反序列化时通过默认构造函数初始化的。
关于Java LinkedBlockingQueue 源代码困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26772311/