+/EE360P
distributed systems
git clone https://git.julia.blue/+/EE360P
cccc41d
master
1import java .util .NoSuchElementException ; 2import java .util .concurrent .atomic .AtomicReference ; 3 4public class LockFreeStack <T > { 5AtomicReference <Node <T >>top =new AtomicReference <Node <T >>(null ); 6 7public void push (T value ) { 8Node <T >node =new Node <T >(value ); 9while (true ) { 10Node <T >oldTop =top .get (); 11node .next =oldTop ; 12if (top .compareAndSet (oldTop ,node ))return ; 13else Thread .yield (); 14 } 15 } 16 17 18public T pop ()throws NoSuchElementException { 19while (true ) { 20Node <T >oldTop =top .get (); 21if (oldTop ==null )throw new NoSuchElementException (); 22T val =oldTop .value ; 23Node <T >newTop =oldTop .next ; 24if (top .compareAndSet (oldTop ,newTop ))return val ; 25else Thread .yield (); 26 } 27 } 28 29 30}