AtomicReference CAS Lock Free Top
Swap a stack head with compareAndSet in a retry loop: the update succeeds only when no other thread moved the reference between read and write.
Code
import java.util.concurrent.atomic.AtomicReference;
public class LockFreeStack {
record Node(String value, Node next) {}
private final AtomicReference<Node> top = new AtomicReference<>(null);
// CAS 重试循环:读到的 top 已被其他线程改动时,compareAndSet 失败并重来
public void push(String value) {
Node oldTop;
Node newTop;
do {
oldTop = top.get();
newTop = new Node(value, oldTop);
} while (!top.compareAndSet(oldTop, newTop));
}
public String pop() {
Node oldTop;
Node newTop;
do {
oldTop = top.get();
if (oldTop == null) {
return null;
}
newTop = oldTop.next();
} while (!top.compareAndSet(oldTop, newTop));
return oldTop.value();
}
public static void main(String[] args) {
LockFreeStack stack = new LockFreeStack();
stack.push("first");
stack.push("second");
System.out.println("pop: " + stack.pop());
System.out.println("pop: " + stack.pop());
System.out.println("empty pop: " + stack.pop());
}
}Inside the snippet
AtomicReference CAS Lock Free Top reduces to the classes LockFreeStack and Node and the functions push, pop and main.
Putting it to use
The signature doing the main work is public void push(String value)
The demo output is labeled (pop:, empty pop:), so the printed output reads as a trace of the operations performed.
The entry point wires push and pop together — run it once and the whole demo flows.
Core lines
return oldTop.value();
Interactive Tools for This Topic
FAQ
- What does AtomicReference CAS Lock Free Top print when run?
- The script runs standalone; its 2 labeled outputs include `pop:`, `empty pop:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.