【发布时间】:2013-12-20 13:33:28
【问题描述】:
我编写了一个 Java 无锁队列实现。它有一个并发错误。我找不到它了。这段代码并不重要。我只是担心我无法解释观察到的与 volatile 变量相关的行为。
异常可见错误(“空头”)。这是不可能的状态,因为存在保持当前队列大小的原子整数。队列有一个存根元素。它规定读线程不改变尾指针,写线程不改变头指针。
队列长度变量保证链表永远不会为空。它就像一个信号量。
take 方法的行为就像它获取了被盗的长度值。
class Node<T> {
final AtomicReference<Node<T>> next = new AtomicReference<Node<T>>();
final T ref;
Node(T ref) {
this.ref = ref;
}
}
public class LockFreeQueue<T> {
private final AtomicInteger length = new AtomicInteger(1);
private final Node stub = new Node(null);
private final AtomicReference<Node<T>> head = new AtomicReference<Node<T>>(stub);
private final AtomicReference<Node<T>> tail = new AtomicReference<Node<T>>(stub);
public void add(T x) {
addNode(new Node<T>(x));
length.incrementAndGet();
}
public T takeOrNull() {
while (true) {
int l = length.get();
if (l == 1) {
return null;
}
if (length.compareAndSet(l, l - 1)) {
break;
}
}
while (true) {
Node<T> r = head.get();
if (r == null) {
throw new IllegalStateException("null head");
}
if (head.compareAndSet(r, r.next.get())) {
if (r == stub) {
stub.next.set(null);
addNode(stub);
} else {
return r.ref;
}
}
}
}
private void addNode(Node<T> n) {
Node<T> t;
while (true) {
t = tail.get();
if (tail.compareAndSet(t, n)) {
break;
}
}
if (t.next.compareAndSet(null, n)) {
return;
}
throw new IllegalStateException("bad tail next");
}
}
【问题讨论】:
-
在不使用锁定机制的情况下,这段代码如何防止数据竞争?为什么不想使用锁?
-
什么时候发现问题?您是通过单个阅读器线程获得它还是需要多个阅读器才能看到问题?我怀疑问题出在 takeOrNull 的第二个 while 循环中存在多个读取器线程。
-
这不是生产代码。把它当作练习。
-
我测试这个队列 100 个读者和 100 个作者。
标签: java queue volatile lock-free