- 非阻塞的栈
public class ConcurrentStack<E> {
AtomicReference<Node<E>> top = new AtomicReference<Node<E>>();
public void put(E item){
Node<E> newHead = new Node<E>(item);
Node<E> oldHead;
do{
oldHead = top.get();
newHead.next = oldHead;
}while(!top.compareAndSet(oldHead,newHead));
}
public E pop(){
Node<E> newHead;
Node<E> oldHead;
do{
oldHead = top.get();
if(oldHead == null)
return null;
newHead = oldHead.next;
}while(!top.compateAndSet(oldHead,newHead));
return oldHead.item;
}
class Node<E>{
public final E item;
public Node<E> next;
public Node(E item){
this.item = item;
}
}
}
- 非阻塞的链表( ConcurrentLinkedQueue实现 )
@ThreadSafe
public class LinkedQueue<E> {
private static class Node<E>{
final E item;
final AtomicReference<Node<E>> next;
public Node(E item,Node<E> next){
this.item = item;
this.next = new AtomicReference<Node<E>>(next);
}
}
private Node<E> dummy = new Node<E>(null,null);
private final AtomicReference<Node<E>> head
= new AtomicReference<Node<E>>(dummy);
private final AtomicReference<Node<E>> tail
= new AtomicReference<Node<E>>(dummy);
public boolean put(E item){
Node<E> newNode = new Node<E>(item,null);
while(true){
Node<E> curTail = tail.get();
Node<E> tailNext = curTail.next.get();
if(curTail == tail.get()){
if(tailNext != null){
tail.compareAndSet(curTail,tailNext);
}else{
if(curTail.next.compareAndSet(null,newNode)){
tail.compareAndSet(curTail,newNode);
return true;
}
}
}
}
}
}
- 在真正的ConcurrentLinkedQueue中,使用原子的域更新器来同步,这样主要是为了省去新建atomicReference的创建过程
private class Node<E>{
private final E item;
private volatile Node<E> next;
public Node(E item){
this.item = item;
}
}
private AtomicReferenceFieldUpdater<Node,Node> nextUpdater
= AtomicReferenceFieldUpdater.newUpdater(Node.class,Node.class,"next");
public static void main(){
Node<String> node = new Node<String>("hahaha");
Node<String> newNode = new Node<String>("I want to be added");
nextUpdater.compareAndSet(node,node.next,newNode);
}