Created
May 8, 2019 15:45
-
-
Save sarxos/228ee848f26fcbb9bb44e475a8f03d47 to your computer and use it in GitHub Desktop.
Concurrent, lock free stack, a Treiber's Stack implementation
This file contains hidden or 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 | |
| * | |
| * 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