+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

vijaygarg1add stack and queuecccc41d

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