Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedBlockingQueue node's next is not volatile

Tags:

java

volatile

I'm reading LinkedBlockingQueue code now, but i have a question, maybe it's simple, but i can't find answer, really need help.

I noticed the Node.next is not volatile, like this:

static class Node<E> {
    E item;
    LinkedBlockingQueue.Node<E> next;

    Node(E var1) {
        this.item = var1;
    }
}

So, how does the enqueue of a new node (Node.next) become visible to the dequeue via another thread?

private void enqueue(Node<E> node) {
    // assert putLock.isHeldByCurrentThread();
    // assert last.next == null;
    last = last.next = node;
}

 private E dequeue() {
    // assert takeLock.isHeldByCurrentThread();
    // assert head.item == null;
    Node<E> h = head;
    Node<E> first = h.next;
    h.next = h; // help GC
    head = first;
    E x = first.item;
    first.item = null;
    return x;
}
like image 625
yuchao Avatar asked Aug 25 '17 03:08

yuchao


1 Answers

Methods enqueue() and dequeue() are private, and thus are invoked ONLY from other methods within that same class, such as peek(), poll(), put(), offer(), etc.

Locking is enforced at a higher level and there's never a chance for two threads to access a node's instance variables at the same time in a race condition.

like image 135
Jim Garrison Avatar answered Oct 26 '22 09:10

Jim Garrison