返回信息流public class LinkedQueue <E> {
private static class Node <E> {
final E item;
final AtomicReference<Node<E>> next;
Node(E item, Node<E> next) {
this.item = item;
this.next = new AtomicReference<Node<E>>(next);
}
}
private AtomicReference<Node<E>> head
= new AtomicReference<Node<E>>(new Node<E>(null, null));
private AtomicReference<Node<E>> tail = head;
public boolean put(E item) {
Node<E> newNode = new Node<E>(item, null);
while (true) {
Node<E> curTail = tail.get();
Node<E> residue = curTail.next.get();
if (curTail == tail.get()) {
if (residue == null) /* A */ {
if (curTail.next.compareAndSet(null, newNode)) /* C */ {
tail.compareAndSet(curTail, newNode) /* D */ ;
return true;
}
} else {
tail.compareAndSet(curTail, residue) /* B */;
}
}
}
}
}
原文链接:http://www.ibm.com/developerworks/cn/java/j-jtp04186/
在看非阻塞队列算法的时候,调了下代码,发现head 和tail在 put结束的时候,始终指向的是同一个值?求分析~
这是一条镜像帖。来源:北邮人论坛 / java / #40833同步于 2015/5/17
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
Michael-Scott 非阻塞队列算法中的插入
nashiyue
2015/5/17镜像同步2 回复
订阅后,新回复会通过你的通知中心匿名送达。
2 条回复
private AtomicReference<Node<E>> tail = head;
这一行有问题吧,这样head和tail都是同一个AtomicReference。如果head和tail是两个可以分别变化的指针,那应该是
private AtomicReference<Node<E>> tail = new AtomicReference<Node<E>>(head.get());
【 在 nuanyangyang 的大作中提到: 】
: : private AtomicReference<Node<E>> tail = head;
:
: ...................
谢谢暖神[ema20]