java 1.5提供了一种无锁队列(wait-free/lock-free)ConcurrentLinkedQueue,可支持多个生产者多个消费者线程的环境:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html
下面这个是网上别人自己实现的一种无锁算法队列,原理和jdk官方的ConcurrentLinkedQueue相似:通过volatile关键字来保证数据唯一性(注:java的volatile和c++的volatile关键字是两码事!),但是里面又用到了atomic,感觉有点boost::lockfree::queue的风格,估计作者是参考了boost的代码来编写这个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;
}
代码出处:
Is this (Lock-Free) Queue Implementation Thread-Safe?
http://stackoverflow.com/questions/1634368/is-this-lock-free-queue-implementation-thread-safe