Introduction
The Java AtomicReference class joined the JDK in Java 5 (2004) as part of JSR 166, the original java.util.concurrent.atomic package. It is a reference type wrapping a volatile reference to an object, supporting atomic read-modify-write operations backed by compare-and-swap (CAS) instructions. AtomicReference makes it possible to update a shared object reference without locks, which is the foundation of lock-free data structures and the standard pattern for immutable-state snapshots.
For a Java learner, the java atomicreference primitive is the right tool whenever you need to atomically swap one object for another, or whenever you need to publish an immutable snapshot of mutable state to many threads. The classic examples are configuration hot-reload, lock-free stacks, and the "immutable holder" pattern where every update creates a new immutable copy of a configuration object. This post walks through the CAS mechanics on references, demonstrates a configuration holder, and shows the compareAndSet pattern that underlies all lock-free algorithms.
What is Java AtomicReference?
The Java AtomicReference class is a holder for a reference to an object of a chosen type. The method set mirrors AtomicInteger and AtomicLong: get, set, getAndSet, compareAndSet, getAndUpdate, updateAndGet, getAndAccumulate, accumulateAndGet. Each operation is atomic because the underlying field is volatile and the CAS loop combines read, modify, and write into a single atomic step.
Conceptually, AtomicReference is the most general of the atomic wrappers. Where AtomicInteger and AtomicLong hold primitive values that are always updated in place, AtomicReference swaps the entire object. This is the right model when the state is naturally immutable: every update creates a brand new object with the desired state, and the AtomicReference atomically swaps the old object for the new one. Readers always see either the old snapshot or the new snapshot, never a mix.
AtomicReference is distinct from a volatile field in one critical way. A volatile field guarantees that writes are visible to readers, but a read-modify-write sequence on a volatile field (read, compute, write) is not atomic: two threads can both read the same old value, both compute new values, and both write, with the second write overwriting the first. AtomicReference's CAS combines the read and write into a single atomic step: the write only happens if the value is still what was read, so concurrent updates do not lose work.
The class is generic: AtomicReference of String holds strings, AtomicReference of List of Integer holds lists, AtomicReference of Config holds configuration objects. The type parameter provides compile-time type safety; the runtime cost is identical regardless of the type.
How Java AtomicReference Works - Step by Step
Step 1: Construction. You write new AtomicReference with an initial value, or new AtomicReference which sets the value to null. The value is stored in a volatile reference field.
Step 2: get and set. get reads the volatile reference; set writes it. Both are atomic; both establish happens-before relationships.
Step 3: compareAndSet(expected, update). The CAS atomically compares the current reference with expected using identity (==) comparison; if they match, the reference is set to update and the call returns true. If they do not match, the reference is unchanged and the call returns false. CAS is the building block for all higher-level atomic operations.
Step 4: getAndSet(newReference). Atomically sets the reference to newReference and returns the old value. This is implemented as a CAS loop and is the simplest atomic swap.
Step 5: updateAndGet(updateFunction) and getAndUpdate(updateFunction). These take a UnaryOperator and apply it atomically; the function is called inside the CAS loop, so it sees the latest value at each retry. The function must be side-effect free because it may be called multiple times.
Step 6: accumulateAndGet(x, accumulatorFunction) and getAndAccumulate. These take an x and a BinaryOperator, applying it as (current, x) -> result. The classic use is to compute a running maximum or minimum of comparable objects.
Java Program for AtomicReference
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class AtomicReferenceDemo {
static final class Config {
final String version;
final Map<String, String> settings;
Config(String version, Map<String, String> settings) {
this.version = version;
this.settings = Collections.unmodifiableMap(new HashMap<>(settings));
}
static Config initial() {
Map<String, String> m = new HashMap<>();
m.put("timeout", "1000");
m.put("retries", "3");
return new Config("v1", m);
}
Config withSetting(String key, String value) {
Map<String, String> copy = new HashMap<>(settings);
copy.put(key, value);
return new Config(version + "+", copy);
}
}
static final class ConfigHolder {
private final AtomicReference<Config> current =
new AtomicReference<>(Config.initial());
Config snapshot() {
return current.get();
}
void update(String key, String value) {
current.updateAndGet(c -> c.withSetting(key, value));
}
}
public static void main(String[] args) throws InterruptedException {
ConfigHolder holder = new ConfigHolder();
System.out.println("initial: " + holder.snapshot().version
+ " timeout=" + holder.snapshot().settings.get("timeout"));
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int t = 0; t < 4; t++) {
final int id = t;
pool.submit(() -> {
for (int i = 0; i < 5; i++) {
String key = "k" + id + "_" + i;
holder.update(key, String.valueOf(id * 10 + i));
}
});
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
Config finalConfig = holder.snapshot();
System.out.println("final version: " + finalConfig.version);
System.out.println("final size: " + finalConfig.settings.size());
System.out.println("sample value k2_3=" + finalConfig.settings.get("k2_3"));
}
}
Code Explanation - Line by Line
The Config class is immutable. Each Config instance holds a version string and an unmodifiable copy of the settings map. The constructor copies the input map into a HashMap and wraps it with Collections.unmodifiableMap so callers cannot mutate the internal state. The withSetting method builds a new Config with one entry replaced, leaving the original Config unchanged.
The ConfigHolder class wraps an AtomicReference of Config initialised with Config.initial. The snapshot method returns current.get(), which is a volatile read; the returned Config is immutable, so callers can use it freely without copying. The update method calls current.updateAndGet(c -> c.withSetting(key, value)), which atomically computes a new Config from the old one and swaps it in.
The update method uses updateAndGet, which internally runs a CAS loop. The function c -> c.withSetting(key, value) reads the current Config, builds a new one, and the CAS tries to swap. If another thread updated the reference between the read and the CAS, the loop retries with the new current value. This is the standard pattern for atomic immutable-state updates.
The main method spawns four threads that each call update five times with distinct keys. The 20 updates run concurrently, but because the CAS loop in updateAndGet is atomic, every update is preserved; no updates are lost. The final Config has 20 keys added on top of the initial 2 (timeout and retries), so the size is 22.
The finalConfig.snapshot().settings.get("k2_3") reads the value that thread 2 wrote for its fourth iteration, which is 2 times 10 + 3 = 23. The output verifies that all updates landed and that the snapshot returned to the main thread reflects every concurrent update.
Sample Input and Output
Input: 4 threads, each calls update 5 times with keys k<thread>_<i> and value thread*10+i Output: initial: v1 timeout=1000 final version: v1++++++++++++++++++++ (20 plus signs after v1) final size: 22 sample value k2_3=23
The initial version is "v1"; each successful update appends a "+" to the version string, so after 20 updates the version is "v1" followed by 20 plus signs. The final size is 22 because there are 2 initial settings plus 20 new ones. The sample value k2_3 is 23 because thread 2 wrote its fourth iteration with value 2 times 10 + 3.
Common Mistakes to Avoid
Mistake 1: Mutating the object referenced by AtomicReference. AtomicReference guarantees atomic swaps of the reference, not atomic mutations of the object. If you call current.get().mutate(), you have a data race; the atomicity is broken the moment you mutate the referenced object. Always treat the referenced object as immutable; build a new object and use compareAndSet or updateAndGet to swap.
Mistake 2: Using equals instead of identity in compareAndSet. The CAS in AtomicReference uses identity (==) comparison, not equals. If you compare with an equal-but-not-identical expected value, the CAS will fail. Always use the exact reference you obtained from get as the expected value.
Mistake 3: Long-running functions in updateAndGet. The UnaryOperator may be called multiple times by the CAS loop if other threads update concurrently. If the function is slow or has side effects, the loop's retries amplify the cost; keep the function fast and pure.
Mistake 4: AtomicReference for multi-variable consistency. CAS only updates one variable atomically; if you have two AtomicReferences that must stay consistent, you cannot update both atomically with separate CAS calls. Combine the two values into a single immutable record and use one AtomicReference to hold that record.
Real-World Applications
Configuration hot reload. The "immutable holder" pattern shown in the demo is the standard way to publish a new configuration to readers without locking; readers do a volatile read of the current reference and use the immutable snapshot. Spring's @ConfigurationProperties and many open-source libraries use this pattern internally.
Lock-free stacks and queues. The classic Michael-Scott queue and the Treiber stack use AtomicReference for the head and tail pointers, with CAS loops to push and pop. The JDK's ConcurrentLinkedQueue and ConcurrentLinkedDeque are built this way.
Immutable snapshot reads. Systems that publish metrics, cache entries, or feature flags use AtomicReference to swap in a new immutable snapshot; readers see either the old snapshot or the new one, with no tearing.
State machines. Concurrent state machines use AtomicReference for the current state; transitions are CAS loops that check the current state and swap to the next state if the precondition holds. This is the foundation of many non-blocking protocol implementations.
Functional reactive programming. Reactive streams that emit immutable events often hold the latest value in an AtomicReference; subscribers read the latest value on subscribe and on each notification. The pattern is common in custom reactive libraries and in some JDK internal helpers.
Conclusion
AtomicReference wraps an object reference with volatile semantics and CAS-based read-modify-write operations, making it the right tool for atomic object swaps and the standard pattern for publishing immutable-state snapshots. It guarantees both atomicity (no torn reads of the reference) and happens-before visibility across threads. The next topics worth studying are AtomicStampedReference for ABA-safe swaps, AtomicInteger and AtomicLong for primitive counters, and VarHandle for the lowest-level atomic primitive underlying the atomic classes.
Comments
Comments
Post a Comment