Mohinish's Blog

Rants from a technologically confused mind !!

Good Read: Non Blocking Algorithm, Non Blocking Stack / LinkedQueue

Java theory and practice: Introduction to nonblocking algorithms
Reference: http://www.ibm.com/developerworks/java/library/j-jtp04186/index.html


public class ConcurrentStack {
AtomicReference<Node> head = new AtomicReference<Node>();

public void push(E item) {
Node newHead = new Node(item);
Node oldHead;
do {
oldHead = head.get();
newHead.next = oldHead;
} while (!head.compareAndSet(oldHead, newHead));
}

public E pop() {
Node oldHead;
Node newHead;
do {
oldHead = head.get();
if (oldHead == null)
return null;
newHead = oldHead.next;
} while (!head.compareAndSet(oldHead,newHead));
return oldHead.item;
}

static class Node {
final E item;
Node next;

public Node(E item) { this.item = item; }
}
}

Advertisement

Written by rootedlabs

September 26, 2011 at 4:25 am

Posted in Java

Follow

Get every new post delivered to your Inbox.