java - 在 ConcurrentLinkedQueue 源代码中无法获取此条件

标签 java concurrency

<分区>

在ConcurrentLinkedQueue的源码中,在offer方法中:

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行,有这样的条件:

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

我知道代码就是把p放到尾部,但是为什么要用这么复杂的代码呢? (p != t && t != (t = tail)) 是什么意思? t!=(t=tail))t!=t 有什么区别?它应该总是假的吗?

有没有资料可以把ConcurrentLinkedQueue说清楚?

最佳答案

这是个有趣的问题,我asked it more broadly there并得到了一些答案。从我能读到的关于这个主题的内容来看:

t != (t = tail) 只是一种奇怪的写法:

if (t != tail)
    t = tail;

简而言之,您正在将 t 的值与分配给右侧 t 的值进行比较,这里是 tail

(所有学分归于 Eran 因为他对主题的理解和他的回答)

所以完整地回答你的问题:

  • 我不知道他们为什么使用如此复杂的代码。
  • (p != t && t != (t = tail)) 表示if p != t and if t != tail t t takes the tail value
  • 差异解释
  • 它不应该总是假的(显然)

关于java - 在 ConcurrentLinkedQueue 源代码中无法获取此条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319047/

相关文章:

java - Switch 多次返回相同的语句

java - 是否可以在我的网站上使用其他网站的搜索结果?

.net - NEventStore乐观锁

cocoa-touch - 从 NSOperation 使用 `performSelectorOnMainThread:withObject:waitUntilDone:` 有多重要?

java - 将图像从 Android 上传到我的服务器(权限被拒绝)

Java多位/紧凑型小整数数组

java - 如何使 JScrollPane 与嵌套的 JTables 一起正常工作?

java - Java并发性–立即关闭线程池

java - 所有线程方法(如 getName/setName)都是线程安全的吗?

java - 何时使用正确版本的单例线程安全实现?