Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

AtomicReference: reading, identity-based CAS, and swapping

Read the current reference, replace it only when it matches the expected reference by identity, or swap it unconditionally and get the previous configuration back.

Version: Java SE 21

Syntax

import java.util.concurrent.atomic.AtomicReference;

// Methods of AtomicReference<V> in Java SE 21:
public final V get()
public final boolean compareAndSet(V expectedValue, V newValue)
public final V getAndSet(V newValue)

In Java SE 21, AtomicReference<V> in java.util.concurrent.atomic holds one reference, which can be null. AtomicReference.get() returns the currently stored reference with volatile read semantics. It neither copies the object nor guarantees that the reference will stay current.

AtomicReference.compareAndSet(expectedValue, newValue) (CAS) atomically compares the current reference with the expected one using ==, not equals(). If both refer to the same object or both are null, it stores newValue and returns true. Otherwise it returns false without writing. The read has volatile semantics, and the write has volatile semantics only when the comparison succeeds.

AtomicReference.getAndSet(newValue) unconditionally stores the new reference and returns the one it replaced, not the new one. Both the read and the write have volatile semantics and form one atomic operation. Separate get() and set() calls do not offer that guarantee: another thread can change the reference between them.

When replacing an immutable configuration, use CAS if your update depends on the instance you read earlier. CAS checks current identity, not history: it cannot detect A → B → A when A is the same reference (the ABA problem). Use getAndSet() when you want to replace the configuration unconditionally and receive exactly the one you displaced. Atomicity applies to the stored reference, not to changes to the object's fields.

Examples

import java.util.concurrent.atomic.AtomicReference;

public class Main {
    record Config(String mode) {}

    public static void main(String[] args) {
        var ref = new AtomicReference<>(new Config("normal"));
        Config observed = ref.get();
        Config equalButDistinct = new Config("normal");
        Config maintenance = new Config("maintenance");

        System.out.println("Equal contents: " + observed.equals(equalButDistinct));
        System.out.println("CAS with distinct object: " + ref.compareAndSet(equalButDistinct, maintenance));
        System.out.println("CAS with observed reference: " + ref.compareAndSet(observed, maintenance));

        Config previous = ref.getAndSet(new Config("recovery"));
        System.out.println("Previous mode: " + previous.mode());
        System.out.println("Current mode: " + ref.get().mode());
    }
}

Result

Equal contents: true
CAS with distinct object: false
CAS with observed reference: true
Previous mode: maintenance
Current mode: recovery

The two distinct `Config` objects have equal contents, but CAS succeeds only with the reference that was read. Then `getAndSet()` returns the `maintenance` configuration even though `recovery` is now stored.

Related lessons

  • Java · Lesson 55 · Intermediate · Version: 2

Sources