Java Concurrency Interview

Atomics and compare-and-swap question 62 of 180 mid

Is AtomicReference enough to make the object it points at thread safe?

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.

atomics immutability

Quiz yourself on Atomics and compare-and-swap Suggest a correction