I experimented with java.util.concurrent and tried to correctly determine how to use AtomicReference.compareAndSet correctly to control concurrent access to a common state unit.
In particular: the correct and safe use of compareAndSet? Any pitfalls?
My test class is a simple stack based on a linked list of nodes.
public class LinkedStack<T> { AtomicReference<Node<T>> topOfStack=new AtomicReference<Node<T>>(); public T push(T e) { while(true) { Node<T> oldTop=topOfStack.get(); Node<T> newTop=new Node<T>(e,oldTop); if (topOfStack.compareAndSet(oldTop, newTop)) break; } return e; } public T pop() { while(true) { Node<T> oldTop=topOfStack.get(); if (oldTop==null) throw new EmptyStackException(); Node<T> newTop=oldTop.next; if (topOfStack.compareAndSet(oldTop, newTop)) return oldTop.object; } } private static final class Node<T> { final T object; final Node<T> next; private Node (T object, Node<T> next) { this.object=object; this.next=next; } } ................... }
source share