/** * ConcurrentStack * * Nonblocking stack using Treiber's algorithm * * @author Brian Goetz and Tim Peierls */ @ThreadSafe publicclassConcurrentStack <E> { AtomicReference<Node<E>> top = new AtomicReference<>();
publicvoidpush(E item){ Node<E> newHead = new Node<>(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) { returnnull; } newHead = oldHead.next; } while (!top.compareAndSet(oldHead, newHead)); return oldHead.item; }
privatestaticclassNode<E> { publicfinal E item; public Node<E> next;