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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With