我最近正在学习Java并发编程。我知道final
关键字可以保证发布的安全性。但是,当我阅读LinkedBlockingQueue
源代码时,发现head
和last
字段未使用final
关键字。我发现enqueue
方法在put
方法中被调用,并且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();
}
}
您正确地认为last
等于node
值的null
。但是,这是故意的。 lock
仅用于确保每个线程都可以正确执行此类中的修改。
有时使用null
值是有意的,以指示缺少值(在这种情况下为空队列)。因为变量是private
,所以只能在类中进行修改,因此,只要编写该类的人知道null
的可能性,一切都很好。
我认为您正在混淆多个未必相关的不同概念。请注意,因为last
为private
,所以没有发布。另外,head
和last
是要修改的,因此不能为final
。
也许您会错过对Java的continuous assignment的理解
//first last is inited in the constructor
last = head = new Node<E>(null); // only the filed's value in last is null(item & next)
// enqueue
last = last.next = node;
//equals:
last.next = node;
last = last.next;
仅当您呼叫last.next
时,否则将没有NPE。