Atomics and compare-and-swap question 62 of 180 mid
Is AtomicReference enough to make the object it points at thread safe?
- Yes, all access through it is synchronized
- Correct: No, it makes replacing the reference atomic; the object behind it must be immutable or separately guarded
- Only for final fields
- Only if the object implements
Serializable
AtomicReference guarantees exactly one thing: reads and writes of the reference are atomic and
visible. Mutating the object it points to is entirely unguarded.
That is why the idiomatic use pairs it with an immutable value and a CAS loop, which gives you an atomic multi-field update without a lock:
record State(int count, long lastSeen) { }
void touch() {
State old;
State next;
do {
old = state.get();
next = new State(old.count() + 1, System.nanoTime());
} while (!state.compareAndSet(old, next));
}
Both fields change together or not at all, and readers always see a consistent pair.
Quiz yourself on Atomics and compare-and-swap Suggest a correction