在ConcurrentLinkedQueue源代码中无法获得此条件 [英] Can't get this condition in ConcurrentLinkedQueue source code

查看:71
本文介绍了在ConcurrentLinkedQueue源代码中无法获得此条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ConcurrentLinkedQueue的源代码中,使用 offer 方法:

In the source code of ConcurrentLinkedQueue, in the offer method:

public boolean offer(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);

for (Node<E> t = tail, p = t;;) {
    Node<E> q = p.next;
    if (q == null) {
        // p is last node
        if (p.casNext(null, newNode)) {
                // Successful CAS is the linearization point
                // for e to become an element of this queue,
                // and for newNode to become "live".
                if (p != t) // hop two nodes at a time
                    casTail(t, newNode);  // Failure is OK.
                    return true;
            }
            // Lost CAS race to another thread; re-read next
        }
        else if (p == q)
            // We have fallen off list.  If tail is unchanged, it
            // will also be off-list, in which case we need to
            // jump to head, from which all live nodes are always
            // reachable.  Else the new tail is a better bet.
            p = (t != (t = tail)) ? t : head;
        else
            // Check for tail updates after two hops.
            p = (p != t && t != (t = tail)) ? t : q;
    }
}

在第352行,存在以下情况:

at line 352, there is this condition:

p = (p != t && t != (t = tail)) ? t : q;

我知道代码会将p放在最后,但是为什么要使用如此复杂的代码呢? (p!= t&& t!=(t = tail))是什么意思? t!=(t = tail)) t!= t 有什么区别?

I know that code is to put p to the tail, but why use so complex code? and what does (p != t && t != (t = tail))mean? what the different between t!=(t=tail)) and t!=t? should it always be false ?

是否有任何材料可以清楚地解释ConcurrentLinkedQueue?

Is there any materials can explain ConcurrentLinkedQueue clearly?

推荐答案

这是一个有趣的问题,我更广泛地提出了这个问题,并得到了一些答案。根据我在该主题上可以读到的内容:

It is an interesting question, I asked it more broadly there and got a few answers. From what I can read on this topic:

t!=(t =尾)只是一种怪异的书写方式:

t != (t = tail) is just a weird way to write:

if (t != tail)
    t = tail;

简而言之,您正在将 t 的值与右边分配给 t 的值,这里是 tail

In short, you are comparing the value of t with the value of what is assigned to t on the right, here tail.

(所有功劳归因于 Eran ,以使他对这个主题和答案有所了解)

( All the credits go to Eran for his understanding of the topic and his answer )

所以要完全回答您的问题:

So to answer your question entirely:


  • 我不知道他们为什么使用如此复杂的代码。

  • (p!= t&&t!=(t =尾巴))表示如果p!= t且如果t!=尾巴t取尾值

  • 差异解释

  • (显然)它不应该总是错误的

  • I don't know why they used so complex code.
  • (p != t && t != (t = tail)) means if p != t and if t != tail t takes the tail value
  • Difference explained
  • It should not be always false (obviously)

这篇关于在ConcurrentLinkedQueue源代码中无法获得此条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆