使用`LinkedBlockingQueue`可能导致空指针异常

我最近正在学习Java并发编程。我知道final关键字可以保证安全的发布。但是,当我阅读LinkedBlockingQueue源代码时,发现headand

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();

}

}

回答:

根据此博客文章https://shipilev.net/blog/2014/safe-public-

construction/甚至final在构造函数中写入一个属性也足以实现安全的初始化(因此,您的对象将始终被安全地发布)。并且capacity属性声明为final

简而言之,我们在以下三种情况下会产生障碍:

最后一个领域是这样写的。注意,我们并不关心实际写入哪个字段,我们在退出(initializer)方法之前无条件地发出了屏障。这意味着,如果您至少有一个final字段写操作,则final字段语义将扩展到构造函数中编写的所有其他字段。

以上是 使用`LinkedBlockingQueue`可能导致空指针异常 的全部内容, 来源链接: utcz.com/qa/412929.html

回到顶部