Hos*_*Aly 11 java multithreading locking thread-safety
我正在尝试用Java创建一个无锁队列实现,主要用于个人学习.队列应该是一般的,允许任意数量的读者和/或作者同时.
您能否回顾一下,并提出您发现的任何改进/问题?
谢谢.
import java.util.concurrent.atomic.AtomicReference;
public class LockFreeQueue<T> {
private static class Node<E> {
E value;
volatile Node<E> next;
Node(E value) {
this.value = value;
}
}
private AtomicReference<Node<T>> head, tail;
public LockFreeQueue() {
// have both head and tail point to a dummy node
Node<T> dummyNode = new Node<T>(null);
head = new AtomicReference<Node<T>>(dummyNode);
tail = new AtomicReference<Node<T>>(dummyNode);
}
/**
* Puts an object at the end of the queue.
*/
public void putObject(T value) {
Node<T> newNode = new Node<T>(value);
Node<T> prevTailNode = tail.getAndSet(newNode);
prevTailNode.next = newNode;
}
/**
* Gets an object from the beginning of the queue. The object is removed
* from the queue. If there are no objects in the queue, returns null.
*/
public T getObject() {
Node<T> headNode, valueNode;
// move head node to the next node using atomic semantics
// as long as next node is not null
do {
headNode = head.get();
valueNode = headNode.next;
// try until the whole loop executes pseudo-atomically
// (i.e. unaffected by modifications done by other threads)
} while (valueNode != null && !head.compareAndSet(headNode, valueNode));
T value = (valueNode != null ? valueNode.value : null);
// release the value pointed to by head, keeping the head node dummy
if (valueNode != null)
valueNode.value = null;
return value;
}
Run Code Online (Sandbox Code Playgroud)
该代码不是线程安全的。考虑putObject(...)
:
public void putObject(T value) {
Node<T> newNode = new Node<T>(value);
Node<T> prevTailNode = tail.getAndSet(newNode);
prevTailNode.next = newNode;
}
Run Code Online (Sandbox Code Playgroud)
next
第二条语句在设置前一个节点的指针之前添加新节点。这仅发生在第三个声明中。因此,有一个窗口,next
其中null
; 即竞争条件。
即使你解决了这个问题,还有一个更隐蔽的问题。next
读取Node 对象字段的线程不一定会看到第二个线程刚刚写入的值。这是 Java 内存模型的结果。在这种情况下,确保后续读取始终看到较早写入值的方法是:
next
为volatile
, 或getObject()
编辑:在阅读和 的代码时putObject()
,更详细地,我可以看到没有任何东西强制将 的非空值next
刷新到内存中putObject
,也没有任何东西强制从主内存中getObject
读取next
。因此,getObject
代码可能会看到错误的值,导致它在队列中确实有元素时next
返回。null
归档时间: |
|
查看次数: |
5040 次 |
最近记录: |