Repository navigation
jdk concurrent concurrentlinkedqueue
wangkaiwu edited this page Jul 11, 2022
·
2 revisions
public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
implements Queue<E>, java.io.Serializable {
transient volatile Node<E> head;
private transient volatile Node<E> tail;
public ConcurrentLinkedQueue() {
head = tail = new Node<E>();
}
}public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
implements Queue<E>, java.io.Serializable {
static final VarHandle NEXT;
public boolean offer(E e) {
final Node<E> newNode = new Node<E>(Objects.requireNonNull(e));
// p = tail
for (Node<E> t = tail, p = t; ; ) {
Node<E> q = p.next;
if (q == null) {
// 说明无竞争
// cas 将 tail.next = newNode
if (NEXT.compareAndSet(p, null, newNode)) {
// 至少第一次循环不会出现这个情况
if (p != t)
TAIL.weakCompareAndSet(this, t, newNode);
return true;
}
} else if (p == q) {
p = (t != (t = tail)) ? t : head;
} else {
p = (p != t && t != (t = tail)) ? t : q;
}
}
}
}第一个元素 offer 后的结果
- tail.next = nodeA
第二个元素 offer 后的结果
- 第一次循环
- q = nodeA
- p = tail
- t = tail
- p = q = nodeA
- 第二次循环
- p = nodeA
- q = p.next = nodeA.next
- nodeA.next = nodeB
- t = tail
- p != t == true
- tail = nodeB