【发布时间】:2020-08-30 10:49:19
【问题描述】:
我最近在学习java并发编程。我知道final 关键字可以保证安全发布。但是,当我阅读LinkedBlockingQueue源代码时,发现head和last字段没有使用final关键字。发现put方法中调用了enqueue方法,enqueue方法直接将值赋值给last.next。此时,last 可能是null,因为last 没有用final 声明。我的理解正确吗?虽然lock可以保证last读写线程安全,但是lock可以保证last是一个正确的初始值而不是null
public class LinkedBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
transient Node<E> head;
private transient Node<E> last;
public LinkedBlockingQueue(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node<E>(null);
}
private void enqueue(Node<E> node) {
// assert putLock.isHeldByCurrentThread();
// assert last.next == null;
last = last.next = node;
}
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();
}
}
【问题讨论】:
-
他们不能是
final,因为他们已经改变了。创建一个变量final并不能保证它永远不会为空。你的问题没有意义。
标签: java null final linkedblockingqueue