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.
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());
First CAS succeeded: true
Second CAS succeeded: false
Current value: updated
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