Skip to content

Instantly share code, notes, and snippets.

@w1shen
Created April 23, 2013 04:25
Show Gist options
  • Save w1shen/5440843 to your computer and use it in GitHub Desktop.
Save w1shen/5440843 to your computer and use it in GitHub Desktop.
public class ConcurrentStack<E> {
AtomicReference<Node<E>> head = new AtomicReference<Node<E>>();
public void push(E item) {
Node<E> newHead = new Node<E>(item);
Node<E> oldHead;
do {
oldHead = head.get();
newHead.next = oldHead;
} while (!head.compareAndSet(oldHead, newHead));
}
public E pop() {
Node<E> oldHead;
Node<E> newHead;
do {
oldHead = head.get();
if (oldHead == null)
return null;
newHead = oldHead.next;
} while (!head.compareAndSet(oldHead,newHead));
return oldHead.item;
}
static class Node<E> {
final E item;
Node<E> next;
public Node(E item) { this.item = item; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment