CKTIS / Java
AtomicReference — updating a reference atomically
AtomicReference<V> provides atomic operations on one reference. Learn how get(), conditional compareAndSet(), and unconditional getAndSet() differ, and why object identity rather than content equality determines whether a conditional replacement succeeds.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
AtomicReference<V> ref = new AtomicReference<>(initialValue);
V current = ref.get();
boolean changed = ref.compareAndSet(expectedValue, newValue);
V previous = ref.getAndSet(newValue);AtomicReference<V> in java.util.concurrent.atomic holds one atomically updatable reference. It protects reference operations, not the referenced object's fields; it does not automatically make that object thread-safe.
AtomicReference.get() reads the reference with volatile read semantics. AtomicReference.compareAndSet(expectedValue, newValue) atomically compares and replaces: it uses ==, not equals(). It returns true after replacement, or false on mismatch without changing the value.
AtomicReference.getAndSet(newValue) unconditionally replaces the reference atomically and returns the previous one. Separate get() and write calls do not form one atomic operation; another thread can act between them.
The example uses one thread for deterministic output. Two new String("ready") objects have equal content but different identities: the first comparison fails, while the second uses the stored reference and succeeds. Documentation scope: Java SE 21; repository runtime and production runtime are not attested.
Examples
import java.util.concurrent.atomic.AtomicReference;
public class Main {
public static void main(String[] args) {
String initial = new String("ready");
AtomicReference<String> ref = new AtomicReference<>(initial);
System.out.println(ref.get());
System.out.println(ref.compareAndSet(new String("ready"), "wrong"));
System.out.println(ref.compareAndSet(initial, "running"));
System.out.println(ref.getAndSet("done"));
System.out.println(ref.get());
}
}Result
ready false true running done
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.