Good Read: Non Blocking Algorithm, Non Blocking Stack / LinkedQueue
Java theory and practice: Introduction to nonblocking algorithms
Reference: http://www.ibm.com/developerworks/java/library/j-jtp04186/index.html
public class ConcurrentStack {
AtomicReference<Node> head = new AtomicReference<Node>();
public void push(E item) {
Node newHead = new Node(item);
Node oldHead;
do {
oldHead = head.get();
newHead.next = oldHead;
} while (!head.compareAndSet(oldHead, newHead));
}
public E pop() {
Node oldHead;
Node newHead;
do {
oldHead = head.get();
if (oldHead == null)
return null;
newHead = oldHead.next;
} while (!head.compareAndSet(oldHead,newHead));
return oldHead.item;
}
static class Node {
final E item;
Node next;
public Node(E item) { this.item = item; }
}
}
