AtomicStampedReference ABA Guard
Pair a version stamp with compareAndSet so the ABA transition back to the original value cannot fool a stale snapshot into swapping.
Code
import java.util.concurrent.atomic.AtomicStampedReference;
public class SlotGuard {
public static void main(String[] args) {
AtomicStampedReference<String> slot = new AtomicStampedReference<>("idle", 0);
// 慢线程缓存它看到的快照:值 idle,版本 0
String seenRef = slot.getReference();
int seenStamp = slot.getStamp();
// 其余线程趁它暂停把槽位归还又占用:idle 变 lease 再变回 idle
slot.compareAndSet("idle", "lease-A", 0, 1);
slot.compareAndSet("lease-A", "idle", 1, 2);
// 值绕回了 idle——只比较引用的 CAS 会被这个 ABA 骗过;
// 带版本戳的 CAS 要求引用与 stamp 同时匹配:版本已是 2,快照是 0 → 失败
boolean accepted = slot.compareAndSet(seenRef, "lease-B", seenStamp, seenStamp + 1);
System.out.println("stale snapshot accepted: " + accepted);
// 拿当前快照的 CAS 正常成功
int currentStamp = slot.getStamp();
boolean fresh = slot.compareAndSet("idle", "lease-B", currentStamp, currentStamp + 1);
System.out.println("fresh snapshot accepted: " + fresh);
System.out.println("current: ref=" + slot.getReference() + " stamp=" + slot.getStamp());
}
}Inside the snippet
Count the class SlotGuard and the function main as the entire surface area of AtomicStampedReference ABA Guard.
Putting it to use
The main signature reads public static void main(String[] args)
Running the file prints labeled results such as stale snapshot accepted:, fresh snapshot accepted:, current: ref= — each operation’s effect is visible in the output.
Core lines
boolean fresh = slot.compareAndSet("idle", "lease-B", currentStamp, currentStamp + 1);
boolean accepted = slot.compareAndSet(seenRef, "lease-B", seenStamp, seenStamp + 1);
AtomicStampedReference<String> slot = new AtomicStampedReference<>("idle", 0);
Interactive Tools for This Topic
FAQ
- What does AtomicStampedReference ABA Guard print when run?
- Invoke the file as-is — the `stale snapshot accepted:`, `fresh snapshot accepted:`, `current: ref=` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.