gpt4 book ai didi

java - ConcurrentLinkedQueue代码解释

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:37 25 4
gpt4 key购买 nike

http://www.java2s.com/Open-Source/Java-Open-Source-Library/7-JDK/java/java/util/concurrent/ConcurrentLinkedQueue.java.htm

以上是ConcurrentLinkedQueue的源码。我无法理解一种情况。

条件 (p == q) 将如何出现在下面的代码片段中,来自 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;
}
}

还有作者所说的“我们已经从名单上掉下来了”是什么意思

最佳答案

ConcurrentLinkedQueue 允许在遍历内部列表时同时修改它。这意味着您正在查看的节点可能已被同时删除。为了检测这种情况,已删除节点的下一个指针更改为指向自身。查看 updateHead (L302) 了解详细信息。

关于java - ConcurrentLinkedQueue代码解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18696343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com