http://fm.csl.sri.com/SSFT13/ConcurrentStack.java
http://baptiste-wicht.com/posts/2010/09/java-concurrency-atomic-variables.html
Here is a thread-safe Stack implemented using AtomicReference
someone pointed to MonotonicClock - a class in Bitronix, which uses AtomicLong & System.nanoTime, to ensure that the Clock always " leaps forward " predictably. I thought you might want to take a look at the class & their succint usage of AtomicLong.
http://baptiste-wicht.com/posts/2010/09/java-concurrency-atomic-variables.html
Here is a thread-safe Stack implemented using AtomicReference
public class Stack { private final AtomicReference<Element> head = new AtomicReference<Element>(null); public void push(String value){ Element newElement = new Element(value); while(true){ Element oldHead = head.get(); newElement.next = oldHead; //Trying to set the new element as the head if(head.compareAndSet(oldHead, newElement)){ return; } } } public String pop(){ while(true){ Element oldHead = head.get(); //The stack is empty if(oldHead == null){ return null; } Element newHead = oldHead.next; //Trying to set the new element as the head if(head.compareAndSet(oldHead, newHead)){ return oldHead.value; } } } private static final class Element { private final String value; private Element next; private Element(String value) { this.value = value; } } }To conclude, atomic variables classes are a really good way to implement non-blocking algorithms and moreover are also a very good alternative to volatile variables, because they can provide atomicity and visibility.
someone pointed to MonotonicClock - a class in Bitronix, which uses AtomicLong & System.nanoTime, to ensure that the Clock always " leaps forward " predictably. I thought you might want to take a look at the class & their succint usage of AtomicLong.