LinkedBlockingQueue#enqueue中last=last.next=node语句含义及last.next=null原因问询
last = last.next = node in LinkedBlockingQueue's enqueue Method Hey there! Let's break down this chained assignment step by step to clear up your confusion, and tie it to how LinkedBlockingQueue works under the hood.
First, How Chained Assignment Works in Java
In Java, an expression like a = b = c follows a right-to-left execution order. It’s equivalent to:
b = c; a = b;
Or more precisely, a = (b = c) — the rightmost assignment runs first, and its result (which is the value assigned to b, i.e., c) is then assigned to a.
Now, Let's Contextualize This with LinkedBlockingQueue
Before diving into the enqueue method, let’s recall a key detail about LinkedBlockingQueue's internal structure: it uses a dummy sentinel node when initialized. That means when you first create a LinkedBlockingQueue, both head and last point to an empty node (with item = null and next = null).
Let’s walk through your code step by step:
You create a new node:
Node node = new Node(1). TheNodeclass inLinkedBlockingQueuelooks roughly like this:static class Node<E> { E item; Node<E> next; Node(E x) { item = x; } }Notice the
nextfield isn’t initialized in the constructor, so it defaults tonullfor your newNode@xxx998(1).When you enter
enqueue(node), the currentlastis pointing to the dummy sentinel node.Now execute
last = last.next = node:- Step 1: Run
last.next = node. This sets thenextfield of the dummy node (the currentlast) to your newNode@xxx998(1). Now the dummy node'snextpoints to your node. - Step 2: The result of
last.next = nodeis the value ofnodeitself (since assignment expressions return the value being assigned). We then assign this result tolast, so nowlastpoints directly to yourNode@xxx998(1).
- Step 1: Run
Why is last.next Null After Execution?
Because your new Node@xxx998(1) was created with next = null (Java initializes unassigned object references to null by default). When last is updated to point to this node, last.next just reflects the node's original, unmodified next field — which is null. This is exactly what we want: the new node becomes the tail of the queue, so its next should be null.
Why Your Search for a=b=c Might Not Have Covered This Case
Chained assignment itself is straightforward, but the confusion here comes from combining it with LinkedBlockingQueue's sentinel node implementation. Generic searches for a=b=c won’t mention this specific queue internals, which is why you didn’t find a matching example.
内容的提问来源于stack exchange,提问作者christmads

