-
-
Save spacejam/b628edb1bb2d67921c936fa8c25983b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.atomic.*; | |
import net.jcip.annotations.*; | |
/** | |
* ConcurrentStack | |
* | |
* retrieved from https://en.wikipedia.org/wiki/Treiber_Stack | |
* | |
* 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