You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LinkedBlockingQueue#enqueue中last=last.next=node语句含义及last.next=null原因问询

Understanding the Chained Assignment 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:

  1. You create a new node: Node node = new Node(1). The Node class in LinkedBlockingQueue looks roughly like this:

    static class Node<E> {
        E item;
        Node<E> next;
        Node(E x) { item = x; }
    }
    

    Notice the next field isn’t initialized in the constructor, so it defaults to null for your new Node@xxx998(1).

  2. When you enter enqueue(node), the current last is pointing to the dummy sentinel node.

  3. Now execute last = last.next = node:

    • Step 1: Run last.next = node. This sets the next field of the dummy node (the current last) to your new Node@xxx998(1). Now the dummy node's next points to your node.
    • Step 2: The result of last.next = node is the value of node itself (since assignment expressions return the value being assigned). We then assign this result to last, so now last points directly to your Node@xxx998(1).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:42:20