Java atomics and VarHandle: Concurrency in Java 25
Learn Java 25 atomics: AtomicInteger, AtomicReference, CAS loops, LongAdder, VarHandle memory modes, and when to choose an atomic or lock.
Learn Java 25 atomics: AtomicInteger, AtomicReference, CAS loops, LongAdder, VarHandle memory modes, and when to choose an atomic or lock.
Java atomics and VarHandle: Concurrency in Java 25
Atomic classes expose thread-safe operations on individual variables; VarHandle lets code access a variable through explicit modes. Not every VarHandle mode is atomic or volatile. The API specifies which operations are atomic and what memory-ordering effects they have; it does not promise that every operation is implemented as a CPU compare-and-swap (CAS) instruction.
Introduction
The Java 25 java.util.concurrent.atomic package describes atomic classes in terms of atomic operations on single variables, arrays, and selected volatile fields. A successful compare-and-set (CAS) is one such operation; get() and set() are access operations with their own memory effects. The package specification associates those effects with VarHandle modes. It does not require every class or method to use a CAS loop internally. See the Java 25 atomic package docs and Java 25 VarHandle docs (checked 2026-11-05).
VarHandle, introduced in Java 9, is a typed handle to a field, array element, or other variable. Its access modes include plain, opaque, acquire/release, volatile, and atomic update operations. The examples below use Java SE 25 names and semantics. Choose the mode that satisfies the algorithm’s correctness requirements; do not assume a weaker mode is faster without measuring the target JVM and hardware.
Keep two questions separate: does the operation update atomically, and what memory ordering does it guarantee?
CAS, atomic access, and locks
CAS compares a variable with an expected value and conditionally updates it as one atomic operation. A retry loop is explicit about what happens when another thread wins first: read again, recalculate, and try again. The API specifies the conditional update and its memory effects; the JVM decides how to implement it.
This complete example uses JDK 25’s AtomicLong API. Save it as CasCounterDemo.java, then run javac --release 25 CasCounterDemo.java && java CasCounterDemo. It prints 1.
import java.util.concurrent.atomic.AtomicLong;
public class CasCounterDemo {
private final AtomicLong value = new AtomicLong();
public long increment() {
long current = value.get();
while (!value.compareAndSet(current, current + 1)) {
current = value.get();
}
return current + 1;
}
public static void main(String[] args) {
var counter = new CasCounterDemo();
System.out.println(counter.increment());
}
}
A lock protects a larger critical section, which can be easier to reason about when several values must change together. A CAS loop can retry repeatedly under contention, and an individual thread may keep losing even while other threads make progress. Measure it against the lock for the workload you have.
AtomicInteger and AtomicLong
AtomicInteger counter = new AtomicInteger(0);
// Basic operations
counter.set(10);
counter.get(); // Returns 10
// Atomic increment
counter.incrementAndGet(); // ++i, returns new value
counter.getAndIncrement(); // i++, returns old value
counter.addAndGet(5); // i += 5, returns new value
counter.getAndAdd(5); // i += 5, returns old value
// Update with function
counter.updateAndGet(x -> x * 2); // Double the value
counter.accumulateAndGet(3, Integer::sum); // Accumulate
// Compare and set (the foundation)
boolean success = counter.compareAndSet(10, 20); // Sets to 20 only if current is 10
For AtomicInteger, get() and set() have volatile memory effects; neither is a CAS read-modify-write. Methods such as incrementAndGet() and compareAndSet() provide atomic updates with their own documented memory effects. These API guarantees do not expose the implementation strategy; see the Java SE 25 AtomicInteger docs (checked 2026-11-05).
AtomicInteger and volatile counters
For a volatile int, each read and write has volatile semantics, but counter++ is still a compound read-modify-write. Two threads can both read 0 and then each write 1, losing one increment. Use an atomic read-modify-write method when the increment itself must be indivisible.
The exact bytecode depends on how the expression is compiled, but the important point is the separate read, calculation, and write. volatile does not combine those steps into one update.
AtomicInteger.incrementAndGet() guarantees an atomic increment and returns the updated value. The API specifies that result and its memory effects, not that the implementation must call compareAndSet in a particular loop.
// BROKEN - not atomic despite volatile
private volatile int counter = 0;
counter++; // Read, increment, write - three operations!
// FIXED - truly atomic
private AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // Atomic read-modify-write
AtomicReference
AtomicReference lets you atomically update object references:
AtomicReference<Node> current = new AtomicReference<>(initialNode);
// Basic operations
current.set(newNode);
Node node = current.get();
// Atomic update
current.compareAndSet(expectedNode, newNode); // Set only if still expected
// Functional updates
current.updateAndGet(node -> node.next()); // Walk the chain
current.accumulateAndGet(node, (n1, n2) -> merge(n1, n2));
Implementing a lock-free singly linked list
public class LockFreeStack<T> {
private final AtomicReference<Node<T>> head = new AtomicReference<>(null);
private static class Node<T> {
final T value;
final Node<T> next;
Node(T value, Node<T> next) {
this.value = value;
this.next = next;
}
}
public void push(T value) {
while (true) {
Node<T> oldHead = head.get();
Node<T> newNode = new Node<>(value, oldHead);
if (head.compareAndSet(oldHead, newNode)) {
return; // Success
}
// head changed, retry
}
}
public T pop() {
while (true) {
Node<T> oldHead = head.get();
if (oldHead == null) return null;
Node<T> newHead = oldHead.next;
if (head.compareAndSet(oldHead, newHead)) {
return oldHead.value;
}
// head changed, retry
}
}
}
In this example, a failed CAS means another operation changed head; the loop reads the new head and tries again. If an algorithm reuses nodes or resources, consider whether it also needs an ABA guard.
VarHandle
Java 25’s VarHandle API lets code access a variable through explicit modes. The atomic package documents its operations by their associated VarHandle memory effects; the public API does not require a particular internal implementation.
public class Counter {
private volatile int count = 0;
// Get a VarHandle for the count field
private static final VarHandle VH;
static {
try {
VH = MethodHandles.lookup()
.findVarHandle(Counter.class, "count", int.class);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new ExceptionInInitializerError(e);
}
}
public int get() {
return (int) VH.getVolatile(this);
}
public void set(int value) {
VH.setVolatile(this, value);
}
public int incrementAndGet() {
return (int) VH.getAndAdd(this, 1) + 1;
}
// Weak CAS with plain memory effects; it may fail spuriously
public boolean weakCompareAndSetPlain(int expect, int update) {
return VH.weakCompareAndSetPlain(this, expect, update);
}
// Strong conditional atomic update with volatile memory effects
public boolean compareAndSet(int expect, int update) {
return VH.compareAndSet(this, expect, update);
}
}
VarHandle memory-order modes
For a VarHandle, bare get() and set() select plain memory effects, even if the field is declared volatile; they do not inherit the declaration’s semantics. getVolatile() and setVolatile() use volatile effects. Acquire and release provide directional ordering: getAcquire() keeps later accesses after the read, and setRelease() keeps earlier accesses before the write. If the acquire observes the matching release on the same variable, earlier writes are visible after the read. This differs from AtomicInteger.get() and set(), whose Java SE 25 API specifies volatile effects.
// Volatile read/write memory effects
VH.getVolatile(this);
VH.setVolatile(this, value);
// Acquire/release ordering
VH.getAcquire(this);
VH.setRelease(this, value);
// Opaque: coherent ordering for accesses to this same variable
VH.getOpaque(this);
VH.setOpaque(this, value);
// Plain access: VarHandle.get/set are not volatile, even for a volatile field
VH.get(this);
VH.set(this, value);
// Atomic update modes have their own documented memory effects
VH.compareAndSet(this, expect, update); // Volatile read-modify-write effects
VH.weakCompareAndSetPlain(this, expect, update); // May fail spuriously; plain effects
VH.weakCompareAndSetAcquire(this, expect, update); // Acquire effects
When to use VarHandle instead of atomic classes
The standard atomic classes cover common single-variable updates. Use them for counters, flags, and reference swaps when their documented operations and memory effects fit. VarHandle is useful when you need access modes for a field or array element that the standard class API does not expose.
VarHandle refers to one variable at a time; it does not make a multi-field update atomic. If several values must change together, group them in an immutable object and conditionally replace one AtomicReference, or protect the group with a lock.
Memory ordering is another reason to use it. A VarHandle exposes plain, opaque, acquire/release, volatile, and atomic-update modes. Pick the weakest mode that is correct for the algorithm only when you can explain the required ordering; do not assume it improves performance across JVMs or processors.
A concrete use is a data structure that publishes a value with release semantics and reads it with acquire semantics. That pairing can establish the needed ordering when the acquire observes the corresponding release. Whether it performs better than volatile access depends on the JVM and hardware, so measure before choosing it for speed.
For simple counters, flags, and lazy initialization, use the standard classes unless you need a specific VarHandle mode. Their APIs make the supported operation and memory effects easier to see.
// Replace a composite state as one atomic reference update
record State(double total, long version) {}
AtomicReference<State> state = new AtomicReference<>(new State(0.0, 0));
state.updateAndGet(old -> new State(old.total() + delta, old.version() + 1));
The update function should be free of side effects because an atomic update method may apply it again after a failed attempt.
LongAdder compared with AtomicLong
LongAdder maintains a sum across one or more variables. Under contention, its set of variables can grow to reduce contention. The Java 25 docs say it usually suits shared statistics better than AtomicLong: under low contention they have similar characteristics, while under high contention LongAdder has higher expected throughput at the cost of more space. This is documented behavior, not a promise for every workload; see the Java 25 LongAdder docs (checked 2026-11-05).
LongAdder adder = new LongAdder();
for (int i = 0; i < 1000; i++) {
adder.increment(); // Add one to the statistics counter
}
long sum = adder.sum(); // Get accumulated value
LongAdder.sum() is not an atomic snapshot. An update racing with the call may not appear in its result; after updates stop, it returns the accumulated total. Use it for statistics, not for sequencing or synchronization decisions.
AtomicFieldUpdater
AtomicFieldUpdater lets you add atomicity to existing fields without replacing them:
public class Person {
volatile int age;
volatile String name;
}
AtomicIntegerFieldUpdater<Person> ageUpdater =
AtomicIntegerFieldUpdater.newUpdater(Person.class, "age");
AtomicReferenceFieldUpdater<Person, String> nameUpdater =
AtomicReferenceFieldUpdater.newUpdater(Person.class, String.class, "name");
// Use on existing objects
Person p = new Person();
ageUpdater.compareAndSet(p, 30, 31);
nameUpdater.compareAndSet(p, "John", "Jane");
One updater instance can target a volatile field across many objects, avoiding one wrapper object per field. The Java 25 package documentation describes these as reflection-based utilities and notes their setup and guarantee tradeoffs; use a VarHandle for new code when its API fits.
What the Java API guarantees
Kinds of atomic APIs
Java SE 25 describes java.util.concurrent.atomic as a toolkit for lock-free, thread-safe operations on variables. The package contains several kinds of API, not one universal CAS wrapper:
AtomicBoolean,AtomicInteger,AtomicLong, andAtomicReferenceexpose access and update methods for one value. Theirget()andset()methods have access semantics; methods such ascompareAndSet()andgetAndAdd()provide atomic updates with documented memory effects.- Array classes provide atomic operations on elements. Field updaters apply atomic operations to selected
volatilefields and are reflection-based utilities. AtomicMarkableReferenceandAtomicStampedReferenceupdate a reference together with a mark or stamp. The caller must still manage the mark or stamp correctly to detect the changes relevant to its algorithm.LongAddermaintains a sum across one or more variables and is intended for shared statistics, not fine-grained synchronization.
The API specifies observable behavior and memory effects. A JVM may use CAS, another primitive, or an optimized implementation for a method; application code must not depend on that choice. See the Java 25 atomic package specification.
graph TD
API[Java 25 atomic API guarantees]
API --> SV[Single-value atomic classes]
SV --> GS[Access methods: get and set]
SV --> RU[Read-modify-write methods: CAS, add, update]
API --> UP[Field updaters on volatile fields]
API --> LA[LongAdder: sum across variables]
API --> VH[VarHandle access modes]
VH --> AM[Plain, opaque, acquire/release, volatile]
VH --> AT[Atomic update modes]
VarHandle memory ordering
VarHandle access modes define both atomicity and ordering. The mode applies even when the underlying field is declared volatile, so mixing modes on one variable requires care. These descriptions follow the Java 25 VarHandle specification (checked 2026-11-05):
- Plain (
get/set): ordinary, non-volatile memory effects with no inter-thread ordering. The specification’s bitwise atomicity guarantee for plain access has limits, includinglonganddoubleon 32-bit platforms. - Opaque (
getOpaque/setOpaque): bitwise atomic and coherently ordered with accesses to the same variable, without ordering constraints for other variables. - Acquire/release (
getAcquire/setRelease): an acquire read orders later accesses after it; a release write orders earlier accesses before it. The intended publication relationship depends on the acquire observing the corresponding release on the same variable. - Volatile (
getVolatile/setVolatile): volatile memory effects, with all volatile operations totally ordered with respect to each other.
Atomic update modes such as compareAndSet, getAndSet, and getAndAdd also have specified memory effects. Their existence does not mean plain get/set are CAS operations, or that the JVM must implement every update with the same instruction sequence.
graph TD
subgraph VarHandle
VH[VarHandle] --> AU[Atomic update modes: compare-and-set, get-and-add]
VH --> VH1[Memory Order Modes]
VH1 --> VH2[getVolatile / setVolatile]
VH1 --> VH3[getAcquire / setRelease]
VH1 --> VH4[opaque / ordered]
end
Production failure scenarios
Scenario 1: ABA problem
// BROKEN - ABA problem
// Thread A sees X, Thread B sees X, changes to Y, changes back to X
// Thread A sees X (looks unchanged) but X was modified in between
AtomicReference<Node> current = new AtomicReference<>(nodeA);
current.compareAndSet(nodeA, nodeB); // Thinks nodeA is still there!
// FIXED - use AtomicStampedReference or AtomicMarkableReference
AtomicStampedReference<Node> stamped = new AtomicStampedReference<>(nodeA, 0);
int[] stampHolder = new int[1];
Node observed = stamped.get(stampHolder);
stamped.compareAndSet(observed, nodeB, stampHolder[0], stampHolder[0] + 1);
The ABA problem: a value changes from A to B and back to A. CAS sees no change even though the value was modified.
Scenario 2: Shared counter under contention
// A valid CAS loop; failed attempts retry from a fresh read
public void highlyContested() {
int current = counter.get();
while (!counter.compareAndSet(current, current + 1)) {
current = counter.get();
}
}
// For a statistics counter, LongAdder is another option
LongAdder adder = new LongAdder();
CAS loops can retry more as contention increases. For statistics, compare an AtomicLong with LongAdder; for state transitions that must remain one exact shared value, keep the atomic variable or use a lock. Measure on the target workload.
Scenario 3: Matching release and acquire
// Writer: initialize data, then publish the flag
// Assume VH refers to this object's `ready` field.
data = 42;
VH.setRelease(this, 1);
// Reader: read data only after observing the published flag
if ((int) VH.getAcquire(this) == 1) {
use(data);
}
The acquire read must observe the corresponding release write for this publication pattern to order the earlier data write before use(data). A release store by itself does not make every later read on another thread safe. Use volatile access when the algorithm requires volatile semantics.
Choosing an approach
| Choice | Semantics | Choose it when |
|---|---|---|
AtomicLong |
One atomic long; each update targets the same value. |
A counter is application state, such as a sequence number, and reads must observe one exact shared value. |
LongAdder |
Contended updates may spread across multiple variables. A concurrent sum() is not an atomic snapshot. |
Many threads update statistics and an inexact total during concurrent updates is acceptable. It is not a sequence-number source. |
Lock |
Protects a whole critical section, so related fields can change under one invariant. | The update spans multiple fields, or the code needs a condition, timed acquisition, or interruptible lock acquisition. Always release it in finally. |
The JDK 25 docs describe LongAdder as similar to AtomicLong under low update contention and as having higher expected throughput under high contention, at the cost of more space. That is an API-level guidance, not a benchmark result for your workload. See the Java SE 25 LongAdder docs and Lock docs.
A VarHandle is not another counter choice. Use it when code needs a particular memory mode or atomic operation on a field or array element that the standard atomic classes do not expose. For an invariant across several values, a lock or one immutable object behind an AtomicReference is easier to reason about than separate atomics.
Reproducing the counter benchmark
The code below compares a shared AtomicLong, a shared LongAdder, and a counter guarded by a nonfair ReentrantLock. The workload is deliberately narrow: every operation increments one shared counter, with no reads. It measures update throughput as contention changes; it does not measure a mixed read/write workload or a multi-field critical section.
Place this class in a standalone Maven project generated from the OpenJDK JMH archetype. Pin the JMH version in the generated pom.xml and keep it with the results.
package bench;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.concurrent.locks.ReentrantLock;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
public class CounterBench {
@State(Scope.Benchmark)
public static class SharedCounters {
final AtomicLong atomic = new AtomicLong();
final LongAdder adder = new LongAdder();
final ReentrantLock lock = new ReentrantLock(false);
long locked;
}
@Benchmark
public long atomicLongIncrement(SharedCounters counters) {
return counters.atomic.incrementAndGet();
}
@Benchmark
public void longAdderIncrement(SharedCounters counters) {
counters.adder.increment();
}
@Benchmark
public long lockIncrement(SharedCounters counters) {
counters.lock.lock();
try {
return ++counters.locked;
} finally {
counters.lock.unlock();
}
}
}
Build the benchmark project with mvn clean verify. Run each thread count in a separate fork set and save the JSON output:
for threads in 1 2 4 8; do
java -jar target/benchmarks.jar 'bench.CounterBench.*' \
-bm thrpt -t "$threads" -wi 5 -w 1s -i 5 -r 1s -f 3 \
-rf json -rff "counter-$threads.json"
done
Record the JDK vendor and build from java -version, the JMH version, OS and kernel, CPU model and core counts, thread count, and the benchmark methods. The harness settings above use five one-second warmups, five one-second measurement iterations, and three forks. The operation mix is 100% increments. For a production read/write mix, add JMH reader/writer groups at the observed ratio and record that ratio; a concurrent LongAdder.sum() remains approximate by design.
No throughput or timing data was collected for this article update. Run the procedure on the target JDK and hardware before using results to choose a counter.
Implementation snippets
Single-producer, single-consumer ring-buffer sketch
This example is limited to one producer and one consumer. The atomic head and tail counters do not reserve distinct slots for multiple producers or multiple consumers; this is not a general multi-producer/multi-consumer ring buffer.
public class RingBuffer<T> {
private final Object[] buffer;
private final int capacity;
private final AtomicInteger tail = new AtomicInteger(0);
private final AtomicInteger head = new AtomicInteger(0);
public RingBuffer(int capacity) {
this.capacity = capacity;
this.buffer = new Object[capacity];
}
public boolean offer(T item) {
int tailNow = tail.get();
int headNow = head.get();
if ((tailNow - headNow) >= capacity) {
return false; // Full
}
buffer[tailNow % capacity] = item;
tail.incrementAndGet();
return true;
}
@SuppressWarnings("unchecked")
public T poll() {
int headNow = head.get();
if (headNow >= tail.get()) {
return null; // Empty
}
T item = (T) buffer[headNow % capacity];
head.incrementAndGet();
return item;
}
}
Custom Atomic Boolean with VarHandle
public class AtomicBoolean {
private volatile int value = 0;
private static final VarHandle VH;
static {
try {
VH = MethodHandles.lookup()
.findVarHandle(AtomicBoolean.class, "value", int.class);
} catch (Exception e) {
throw new Error(e);
}
}
public AtomicBoolean(boolean initial) {
VH.setVolatile(this, initial ? 1 : 0);
}
public final boolean get() {
return (int) VH.getVolatile(this) != 0;
}
public final boolean compareAndSet(boolean expected, boolean update) {
return VH.compareAndSet(this,
expected ? 1 : 0,
update ? 1 : 0);
}
public final void set(boolean newValue) {
VH.setVolatile(this, newValue ? 1 : 0);
}
}
Observability checklist
- Are you using atomics for simple counters or flags only?
- Can you detect retry storms under high contention?
- Do you understand the memory ordering semantics you’re using?
- Are you handling the ABA problem where relevant?
- Can you measure atomic vs lock performance for your workload?
- Is
LongAdderused only where a concurrentsum()need not be an atomic snapshot?
Security notes
Lock-free algorithms can expose timing side channels:
- Retry counts can leak information about contention
- Contention on shared counters can create observable timing patterns
- Compare-and-set failures can leak information about operation timing
Use constant-time operations where security-sensitive decisions depend on timing.
Common pitfalls and anti-patterns
- Using atomics where locks are clearer: If in doubt, prefer readability
- Ignoring the ABA problem: Use stamped references for reference-based structures
- Wrong memory ordering: Use volatile semantics unless you understand the tradeoffs
- Retrying forever under contention: For statistics, consider
LongAdder; for coordinated state, consider a lock or a different algorithm - Treating atomicity and ordering as the same property: Check the operation’s documented memory effects
- Forgetting about long vs int: AtomicLong for values > 2^31
Quick recap
- CAS provides an atomic conditional update; a CAS retry loop is application code
- AtomicInteger exposes atomic read-modify-write methods as well as access methods
- AtomicReference atomically updates a reference; it does not make a multi-field update atomic
- VarHandle exposes plain, opaque, acquire/release, volatile, and atomic update modes
- LongAdder is intended for shared statistics; a concurrent sum is not an atomic snapshot
- ABA problem requires stamped/marked references to solve
- Choose memory ordering from the algorithm’s requirements, not an assumed speed advantage
- Retry loops must handle contention and failed attempts
Interview questions
CAS is an atomic conditional update: it compares a variable with an expected value and writes the new value only if they match. Java exposes it through methods such as compareAndSet(); the API guarantee does not prescribe a particular hardware instruction.
A strong compare-and-set returns false when the expected value does not match. A retry loop is separate application logic: read the current value again, recompute, and retry if the operation's semantics allow it.
Whether CAS or a lock performs better depends on the operation, contention, JVM, and hardware. Measure both with a representative workload.
The ABA problem occurs when a value changes from A to B and back to A between the time a thread reads it and the time it tries to CAS. The CAS operation sees the value as unchanged (still A), even though it was actually modified.
This matters for lock-free data structures using CAS. A thread might think a node is still in a list because it sees the same reference, but the node was removed, recycled, and re-added with different contents.
AtomicStampedReference and AtomicMarkableReference pair a reference with a stamp or mark. The algorithm must advance the stamp or toggle the mark when the relevant change occurs; these classes do not update that metadata for you.
The Java 25 API docs describe LongAdder as usually preferable for a shared sum used for statistics: it has characteristics similar to AtomicLong under low contention and higher expected throughput under high contention, at the cost of more space. This is not a workload-specific benchmark result.
Use AtomicLong when each update and read needs one shared atomic value, such as a sequence number. Use LongAdder when many threads update statistics and an exact snapshot during concurrent updates is unnecessary.
LongAdder.sum() is not an atomic snapshot. Updates racing with the sum may not be included; once updates have stopped, it returns the accumulated total.
A VarHandle is a typed handle to a field, array element, or other variable. Java SE 25 defines access modes for plain, opaque, acquire/release, volatile, and atomic updates. The atomic package specifies memory effects through associated VarHandle operations, but the public API does not promise a specific implementation underneath.
Use a VarHandle when you need access modes for a variable that a standard atomic class does not expose. For common counters and reference swaps, the standard atomic APIs are usually easier to read.
Choose an access mode for its ordering and atomicity guarantees. A weaker mode is not automatically faster on every JVM and processor.
compareAndSet provides volatile memory effects and returns whether the expected value matched. In Java 25, VarHandle also has weak variants with plain, acquire, release, or volatile effects; a weak operation may fail spuriously even when the values match.
Choose the variant whose ordering is required by the algorithm. A weak variant is useful only when the code can handle spurious failure; do not select it based on an assumed speed advantage.
AtomicReference.compareAndSet(expected, update) atomically checks the current reference and replaces it only if it matches expected. The Java API specifies the conditional update and its memory effects, not whether a JVM uses one machine instruction or another implementation.
AtomicIntegerFieldUpdater and its long/reference variants operate on a designated volatile field across instances. This can avoid a separate atomic wrapper object for every target field. The Java 25 API describes field updaters as reflection-based utilities with more awkward setup and weaker guarantees than the single-value classes.
Use one when it fits an existing class design and the field's access requirements. For new code, compare it with a VarHandle; performance and memory tradeoffs depend on the workload and runtime.
VarHandle access modes include plain, opaque, acquire/release, and volatile:
- Plain:
get()/set()have non-volatile memory effects and no inter-thread ordering. - Opaque:
getOpaque()/setOpaque()are bitwise atomic and coherently ordered for accesses to the same variable. - Acquire / Release:
getAcquire()orders later accesses after the read;setRelease()orders earlier accesses before the write. The publication protocol must pair them on the same variable. - Volatile:
getVolatile()/setVolatile()use volatile memory effects. These operations are totally ordered with respect to one another.
Atomic update modes such as compareAndSet() also have specified memory effects. Check each method rather than assuming the access mode from the field declaration.
Atomicity and ordering are separate properties. In Java 25, each atomic-class method has documented memory effects associated with VarHandle modes. For example, the standard AtomicInteger.get() and set() use volatile effects, while classes also expose methods with plain, opaque, acquire, or release effects.
When a volatile read observes a volatile write, the Java Memory Model defines the corresponding visibility relationship. For weaker access modes, follow the mode's specific ordering rules rather than assuming every atomic operation creates the same happens-before edge.
Yes. A lock-free stack uses AtomicReference at the head. Push creates a new node with next pointing to the current head, then CAS the head from oldHead to newNode. If another thread modified the head in the meantime, the CAS fails and you retry with the new head.
Pop reads the current head, sets newHead to head.next, then CASes head to newHead. If that CAS fails because another operation changed head first, retry with the current head.
In Java 25 atomic classes, lazySet() has the memory effects of a VarHandle release-mode store. It orders earlier accesses before the write, but it does not have all the ordering properties of a volatile set(). It does not promise a fixed delay before another thread sees the value, and it should be used only when release semantics fit the publication protocol. Its performance relative to set() depends on the JVM and hardware.
getAndSet(newValue) atomically replaces the reference and returns the old value. compareAndSet(expect, update) replaces it only when the current reference matches expect and returns a boolean. Use the first for an unconditional swap and the second for a conditional update. The API specifies the results and memory effects, not the implementation strategy.
AtomicStampedReference updates a reference together with an integer stamp; a conditional update fails if either expected value differs. The algorithm must advance the stamp when relevant changes occur. AtomicMarkableReference pairs a reference with a boolean mark, which can represent a state such as "removed". A mark is not a version counter and does not record how many changes occurred.
updateAndGet(function) applies a unary function to the current value and returns the updated value. accumulateAndGet(value, function) applies a binary function to the current value and the supplied value, then returns the result. For example, the unary function can double a value; the binary function can add a supplied amount. Since an update may be retried after contention, these functions should be side-effect-free. The API does not promise an allocation or performance advantage for either method.
In Java 25, VarHandle.compareAndSet() is an atomic update with volatile read/write memory effects. The API also provides compare-and-exchange and weak compare-and-set variants with acquire, release, or plain effects. Select a variant only when its documented ordering matches the algorithm; do not assume weaker ordering reduces overhead.
getVolatile() has volatile read effects and participates in the total order of volatile operations. getAcquire() orders subsequent accesses after the read; when it observes a matching release write to the same variable, it gives the intended publication ordering. Neither method promises a particular barrier sequence or relative cost across platforms.
The Java 25 atomic package specification describes atomic operations through associated VarHandle effects. That describes the API contract; it does not require a particular JVM implementation such as VarHandle calls, Unsafe, or a specific machine instruction. Use standard atomic classes for the operations they expose, and VarHandle when you need its access modes for a variable.
An AtomicIntegerFieldUpdater operates on a designated volatile int field across instances, so the application does not need a separate atomic wrapper for every object field. The Java 25 package docs describe field updaters as reflection-based utilities with more awkward setup and weaker guarantees. Compare memory use and performance on the target workload rather than assuming a fixed cost versus AtomicInteger.
False sharing can occur when threads update independent values that occupy the same hardware cache line. Cache-line size and object layout depend on the processor, JVM, and runtime options. LongAdder spreads updates across variables to reduce contention, but its public API does not promise a particular memory layout. Measure before adding padding or replacing adjacent fields with per-thread state.
Use VarHandle when you need a specific access mode for a field or array element that a standard atomic class does not expose, or when implementing a concurrent data structure that needs those semantics. A VarHandle operation addresses one variable; it cannot atomically update a separate timestamp field at the same time. Put related state in one immutable object and replace an AtomicReference, or protect the fields with a lock. For ordinary counters and reference swaps, the standard atomic APIs are simpler.
Further reading
- Java Memory Model: Happens-Before, Volatile, and Final Fields — Memory visibility guarantees underpinning atomics
- Java Concurrent Collections — When to use collections vs atomics
- Oracle Java 25 VarHandle documentation — Memory order modes and operations
- Oracle Java 25 AtomicStampedReference documentation — ABA problem solutions
- Advanced Java & JVM Internals Roadmap — Parent roadmap for this topic
Conclusion
Java’s atomic APIs expose atomic updates and memory-ordering modes for individual variables. Use AtomicLong when reads and updates need one shared value, LongAdder for statistics that tolerate a non-snapshot sum during concurrent updates, and a lock when related fields must change together. Use VarHandle modes only when you need their specific guarantees, and measure performance with your target JDK and workload. Continue with Java Memory Model for the visibility rules behind these operations.
Category
Related Posts
Java Concurrent Collections: Maps and Queues
Java concurrent collections deep dive: ConcurrentHashMap, BlockingQueue, CopyOnWriteArrayList, ConcurrentLinkedQueue, and choosing the right structure.
Java Memory Model: Happens-Before, Volatile, Final Fields
Understanding happens-before guarantees, volatile field semantics, and final field safety in the Java Memory Model for correct concurrent code.
Java Concurrency: Executors, ForkJoinPool, Synchronizers
Master Java's java.util.concurrent: Executors, ForkJoinPool, CountDownLatch, CyclicBarrier, Phaser, and thread pool patterns for high-performance apps.