Skip to content

Instantly share code, notes, and snippets.

@liuzhengyang
Created April 7, 2016 03:19
Show Gist options
  • Save liuzhengyang/269e5999d515cff3a1c6b451e003e13a to your computer and use it in GitHub Desktop.
Save liuzhengyang/269e5999d515cff3a1c6b451e003e13a to your computer and use it in GitHub Desktop.
Concurrent Stack
/**
* Description: Concurrent Stack
*
* @author liuzhengyang
* @version 1.0
* @since 2016-04-07
*/
public class ConcurrentStack<E> {
private AtomicReference<Node<E>> top = new AtomicReference<>();
public void push(E item) {
Node<E> newHead = new Node<>(item);
Node<E> old = null;
do {
old = top.get();
newHead.next = old;
} while(!(top.compareAndSet(old, newHead)));
}
public E pop() {
Node<E> oldHead;
Node<E> newHead;
do {
oldHead = top.get();
if (oldHead == null) {
return null;
}
newHead = oldHead.next;
} while (!(top.compareAndSet(oldHead, newHead)));
return oldHead.item;
}
public boolean isEmpty() {
return top.get() == null;
}
public E peek() {
if (top.get() == null) {
return null;
} else {
return top.get().item;
}
}
private static class Node<E> {
private E item;
private 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