Multithreading: AtomicReference does CAS on object references

compareAndSet only replaces the held reference if it still equals the expected one, so a second attempt with a stale expected value is silently rejected. This is the reference-typed counterpart to compare-and-swap on numbers.

Code
AtomicReference<String> ref = new AtomicReference<>("initial");
boolean updated = ref.compareAndSet("initial", "updated");
boolean rejected = ref.compareAndSet("initial", "should not apply");
System.out.println("First CAS succeeded: " + updated);
System.out.println("Second CAS succeeded: " + rejected);
System.out.println("Current value: " + ref.get());
Output
First CAS succeeded: true
Second CAS succeeded: false
Current value: updated
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms