import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReference; public class LockFreeStack { AtomicReference> top = new AtomicReference>(null); public void push(T value) { Node node = new Node(value); while(true) { Node oldTop = top.get(); node.next = oldTop; if (top.compareAndSet(oldTop, node)) return; else Thread.yield(); } } public T pop() throws NoSuchElementException { while(true) { Node oldTop = top.get(); if(oldTop == null) throw new NoSuchElementException(); T val = oldTop.value; Node newTop = oldTop.next; if(top.compareAndSet(oldTop, newTop)) return val; else Thread.yield(); } } }