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

问题描述 投票:0回答:2

我最近正在学习Java并发编程。我知道final关键字可以保证发布的安全性。但是,当我阅读LinkedBlockingQueue源代码时,发现headlast字段未使用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();
    }
}
java null final linkedblockingqueue
2个回答
0
投票

您正确地认为last等于node值的null。但是,这是故意的。 lock仅用于确保每个线程都可以正确执行此类中的修改。

有时使用null值是有意的,以指示缺少值(在这种情况下为空队列)。因为变量是private,所以只能在类中进行修改,因此,只要编写该类的人知道null的可能性,一切都很好。

我认为您正在混淆多个未必相关的不同概念。请注意,因为lastprivate,所以没有发布。另外,headlast是要修改的,因此不能为final


0
投票

也许您会错过对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。

© www.soinside.com 2019 - 2024. All rights reserved.