Skip to content

Instantly share code, notes, and snippets.

@sarxos
Created May 8, 2019 15:45
Show Gist options
  • Select an option

  • Save sarxos/228ee848f26fcbb9bb44e475a8f03d47 to your computer and use it in GitHub Desktop.

Select an option

Save sarxos/228ee848f26fcbb9bb44e475a8f03d47 to your computer and use it in GitHub Desktop.
Concurrent, lock free stack, a Treiber's Stack implementation
import java.util.concurrent.atomic.*;
import net.jcip.annotations.*;
/**
* ConcurrentStack
*
* Nonblocking stack using Treiber's algorithm
*
* @author Brian Goetz and Tim Peierls
*/
@ThreadSafe
public class ConcurrentStack <E> {
AtomicReference<Node<E>> top = new AtomicReference<Node<E>>();
public void push(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> oldHead;
Node<E> newHead;
do {
oldHead = top.get();
if (oldHead == null)
return null;
newHead = oldHead.next;
} while (!top.compareAndSet(oldHead, newHead));
return oldHead.item;
}
private static class Node <E> {
public final E item;
public 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