为什么在AbstractQueuedSynchronize enq(final Node node)方法中有for(;;)

时间:2018-10-10 09:38:34

标签: java java.util.concurrent

当我阅读AbstractQueuedSynchronize源代码时,关于方法

private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

我想知道为什么会有for循环,因为它可能像这样:

private Node enq(final Node node) {
        Node t = tail;
        if (t == null) { // Must initialize
            if (compareAndSetHead(new Node()))
                tail = head;
        } 
        node.prev = tail;
        if (compareAndSetTail(t, node)) {
            t.next = node;
            return t;
        }
}

这与并发有关系吗?

2 个答案:

答案 0 :(得分:1)

该语法用于表示内部内容将无限次执行。它与:

while(true){..}

这意味着内部必须有一条语句可以中断此无限执行,可以是 break return

在您的情况下,这是一个 return 语句,并且无限循环用于执行相同的任务,直到您达到满足 return 的条件为止。这仅在用于检查退出条件的状态中有进度/更改时才有效。在这种情况下,更改是通过跟随链接列表数据结构中的链接进行的。

答案 1 :(得分:0)

您的重写代码不是等效代码。在您的版本中,如果对compareAndSetHead(new Node())的调用评估为false,则tailnull的位置仍为node.prev = tail;

包裹在for (;;) { ... }中的原件将继续尝试,直到tail不是{null}。