Skip to content

Instantly share code, notes, and snippets.

@liuzhengyang
Created April 7, 2016 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuzhengyang/24eaf4335cdb67563820fa11eeccaf70 to your computer and use it in GitHub Desktop.
Save liuzhengyang/24eaf4335cdb67563820fa11eeccaf70 to your computer and use it in GitHub Desktop.
stack concurrent
package com.lzy.algo.collect;
import java.util.concurrent.atomic.AtomicReference;
/**
* 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