VarHandle: atomic field access and memory ordering
A VarHandle is a typed reference to a variable (a field, a static field, an array element or a view into a byte array) that supports atomic operations and a choice of memory ordering. It arrived in Java 9 (JEP 193) as the supported replacement for sun.misc.Unsafe, and much of java.util.concurrent is built on it. This page explains the access modes, runs atomic updates on fields, arrays and byte views, shows release/acquire publication and its limit with a real reordering test, and measures what each mode costs.
Contents
What a VarHandle is
A java.lang.invoke.VarHandleintlongbyte[]ByteBufferMethodHandles.Lookupstatic final
Before Java 9, libraries reached for sun.misc.Unsafe
| Mode | Methods | Guarantees | Best for |
|---|---|---|---|
| Plain | getset | Like a normal field: no ordering or visibility promises between threads | Single-threaded access to the same variable |
| Opaque | getOpaquesetOpaque | The access really happens and is eventually visible; no ordering with other variables | Progress flags and counters read approximately |
| Acquire / release | getAcquiresetRelease | Writes before a release are visible to a thread whose acquire reads that value | Publishing data from one thread to another |
| Volatile | getVolatilesetVolatile | Same as a volatile | When in doubt; flags read and written by many threads |
| Atomic updates | compareAndSetcompareAndExchangegetAndAddgetAndSetgetAndBitwiseOr | Atomic read-modify-write, volatile ordering unless the name says otherwise | Lock-free counters and state machines |
Most application code should use the
Atomic updates on an ordinary field
Four threads each add 1 to a counter 250,000 times through a VarHandle, and update a plain field with ++
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.invoke.WrongMethodTypeException;
public class CasCounter {
private volatile int value; // updated through the VarHandle
private int plain; // updated with ordinary ++ for comparison
private volatile int max;
private static final VarHandle VALUE;
private static final VarHandle MAX;
static {
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
VALUE = lookup.findVarHandle(CasCounter.class, "value", int.class);
MAX = lookup.findVarHandle(CasCounter.class, "max", int.class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
// A compare-and-set retry loop: the pattern behind every lock-free update
void recordMax(int candidate) {
int current;
do {
current = (int) MAX.getVolatile(this);
if (candidate <= current) {
return;
}
} while (!MAX.compareAndSet(this, current, candidate));
}
public static void main(String[] args) throws InterruptedException {
CasCounter c = new CasCounter();
int threads = 4;
int perThread = 250000;
Thread[] workers = new Thread[threads];
for (int t = 0; t < threads; t++) {
int id = t;
workers[t] = new Thread(() -> {
for (int i = 0; i < perThread; i++) {
VALUE.getAndAdd(c, 1);
c.plain++;
c.recordMax(id * perThread + i);
}
});
workers[t].start();
}
for (Thread w : workers) {
w.join();
}
System.out.println("expected: " + threads * perThread);
System.out.println("VarHandle getAndAdd: " + c.value);
System.out.println("plain ++: " + c.plain + " (varies; lost some: "
+ (c.plain < threads * perThread) + ")");
System.out.println("max seen: " + c.max);
try {
VALUE.getAndAdd(c, 1L); // long argument for an int field
} catch (WrongMethodTypeException e) {
System.out.println("1L for an int field: " + e.getClass().getSimpleName());
}
}
}
Output:
expected: 1000000
VarHandle getAndAdd: 1000000
plain ++: 557770 (varies; lost some: true)
max seen: 999999
1L for an int field: WrongMethodTypeException
reached exactly 1,000,000; the plaingetAndAdd lost updates, a different number on every run. The VarHandle made the field atomic without turning it into an++ object.AtomicInteger is the general compare-and-set loop: read the current value, give up if the candidate is not larger, otherwise try to swap and retry if another thread got there first. The result, 999,999, is the largest value any thread offered.recordMax- Passing
for an1L field threwint . The check happens at the call, because the handle's methods takeWrongMethodTypeException in source code but are linked to the exact types used.Object... - Two variants of compare-and-set are worth knowing.
returns the value it found instead of a boolean, which saves a separate read when the loop has to retry.compareAndExchange may fail even when the value matches, which lets it compile to a cheaper instruction on some CPUs such as ARM; it is meant for retry loops like this one, never for a single attempt.weakCompareAndSet - The handle is looked up once, in a static initializer, with
. Looking it up per call would be slow and would defeat the JIT.findVarHandle(class, name, type)
Publishing data with release and acquire
A producer writes a plain field and then sets a flag with setReleasegetAcquirevolatilefinal
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.invoke.VarHandle.AccessMode;
public class AccessModes {
static int data; // plain field, no volatile
static boolean ready; // plain field, published with release/acquire
final int id = 7;
static final VarHandle READY;
static final VarHandle ID;
static {
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
READY = lookup.findStaticVarHandle(AccessModes.class, "ready", boolean.class);
ID = lookup.findVarHandle(AccessModes.class, "id", int.class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
public static void main(String[] args) throws InterruptedException {
Thread consumer = new Thread(() -> {
// getAcquire: later reads cannot move before this read
while (!(boolean) READY.getAcquire()) {
Thread.onSpinWait();
}
System.out.println("consumer saw ready, data = " + data);
});
consumer.start();
data = 42; // plain write
READY.setRelease(true); // setRelease: earlier writes cannot move after this write
consumer.join();
// A VarHandle on a final field supports only the read modes
AccessModes obj = new AccessModes();
System.out.println("final field get: " + (int) ID.get(obj));
for (AccessMode m : new AccessMode[] {AccessMode.GET, AccessMode.GET_ACQUIRE,
AccessMode.SET, AccessMode.COMPARE_AND_SET}) {
System.out.println(" " + m + " supported: " + ID.isAccessModeSupported(m));
}
}
}
Output:
consumer saw ready, data = 42
final field get: 7
GET supported: true
GET_ACQUIRE supported: true
SET supported: false
COMPARE_AND_SET supported: false
- The consumer saw
. A release write guarantees that every write before it in the producer is visible to a thread whose acquire read sees the released value: the same publication guarantee as adata = 42 flag, with a cheaper write on most CPUs.volatile - The handle on the
field supports the read modes but notfinal orSET .COMPARE_AND_SET lets generic code check before calling.isAccessModeSupported - Release/acquire orders only one direction for each side, which the next section shows going wrong.
Where release/acquire is weaker than volatile
The classic store-buffer test from the xyyx
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.CyclicBarrier;
public class OrderingModes {
static int x;
static int y;
static int r1;
static int r2;
static final VarHandle X;
static final VarHandle Y;
static {
try {
var l = MethodHandles.lookup();
X = l.findStaticVarHandle(OrderingModes.class, "x", int.class);
Y = l.findStaticVarHandle(OrderingModes.class, "y", int.class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
// Thread A: write x, read y. Thread B: write y, read x. Can both read 0?
public static void main(String[] args) throws Exception {
int rounds = 1000000;
int relAcq = race(rounds,
() -> { X.setRelease(1); r1 = (int) Y.getAcquire(); },
() -> { Y.setRelease(1); r2 = (int) X.getAcquire(); });
int vol = race(rounds,
() -> { X.setVolatile(1); r1 = (int) Y.getVolatile(); },
() -> { Y.setVolatile(1); r2 = (int) X.getVolatile(); });
System.out.println("rounds per mode: " + rounds);
System.out.println("release/acquire, both read 0: " + relAcq + " times");
System.out.println("volatile, both read 0: " + vol + " times");
}
static int race(int rounds, Runnable a, Runnable b) throws Exception {
CyclicBarrier start = new CyclicBarrier(2);
CyclicBarrier end = new CyclicBarrier(3);
Thread ta = new Thread(() -> loop(rounds, start, end, a));
Thread tb = new Thread(() -> loop(rounds, start, end, b));
ta.start();
tb.start();
int hits = 0;
for (int i = 0; i < rounds; i++) {
end.await();
if (r1 == 0 && r2 == 0) {
hits++;
}
x = 0;
y = 0;
end.await();
}
ta.join();
tb.join();
return hits;
}
static void loop(int rounds, CyclicBarrier start, CyclicBarrier end, Runnable body) {
try {
for (int i = 0; i < rounds; i++) {
start.await();
body.run();
end.await();
end.await();
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
Output (the release/acquire count varies between runs and can be 0; the volatile count is always 0):
rounds per mode: 1000000
release/acquire, both read 0: 1 times
volatile, both read 0: 0 times
- With release and acquire, both threads sometimes read 0: once in this run of a million rounds, and between 0 and a handful of times in repeated runs. Release prevents earlier accesses from moving after the write; acquire prevents later accesses from moving before the read. Nothing stops a release write followed by an acquire read of another variable from being reordered, which is exactly what the CPU's store buffer does.
- With volatile accesses the count is 0, guaranteed: volatile reads and writes take part in a single total order. On x86 the JIT adds a full fence after each volatile write to get this.
- So acquire/release is right for one-way hand-off, as in the producer and consumer above, and wrong for algorithms where two threads each write their own flag and read the other's, such as Dekker-style mutual exclusion.
Array elements and byte array views
Two factory methods produce handles that are not tied to a named field: one for the elements of an int[]intbyte[]
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.stream.IntStream;
public class ArraysAndBytes {
static final VarHandle INTS = MethodHandles.arrayElementVarHandle(int[].class);
static final VarHandle BIG = MethodHandles.byteArrayViewVarHandle(int[].class,
ByteOrder.BIG_ENDIAN);
static final VarHandle LITTLE = MethodHandles.byteArrayViewVarHandle(int[].class,
ByteOrder.LITTLE_ENDIAN);
public static void main(String[] args) {
// Atomic updates on individual array slots, like AtomicIntegerArray but on a plain int[]
int[] histogram = new int[4];
IntStream.range(0, 1000000).parallel()
.forEach(i -> INTS.getAndAdd(histogram, i % 4, 1));
System.out.println("histogram: " + Arrays.toString(histogram));
// Reading and writing an int inside a byte[] at a byte offset
byte[] bytes = new byte[8];
BIG.set(bytes, 0, 0x0A0B0C0D);
LITTLE.set(bytes, 4, 0x0A0B0C0D);
System.out.println("bytes: " + HexFormat.ofDelimiter(" ").formatHex(bytes));
System.out.printf("read big-endian at 0: 0x%08X%n", (int) BIG.get(bytes, 0));
System.out.printf("read big-endian at 4: 0x%08X%n", (int) BIG.get(bytes, 4));
try {
BIG.get(bytes, 6); // needs bytes 6..9, the array has 8
} catch (IndexOutOfBoundsException e) {
System.out.println("offset 6: IndexOutOfBoundsException");
}
}
}
Output:
histogram: [250000, 250000, 250000, 250000]
bytes: 0a 0b 0c 0d 0d 0c 0b 0a
read big-endian at 0: 0x0A0B0C0D
read big-endian at 4: 0x0D0C0B0A
offset 6: IndexOutOfBoundsException
- A parallel stream incremented four slots of a plain
atomically, 250,000 times each, without anint[] . The handle takes the array and the index as its first arguments.AtomicIntegerArray - The byte view wrote
big-endian at offset 0 and little-endian at offset 4, and the bytes show both orders. Reading the second one back as big-endian gave0x0A0B0C0D , the classic symptom of a byte-order mistake when parsing binary data.0x0D0C0B0A - Offset 6 would need bytes 6 to 9 of an 8-byte array and threw
, where Unsafe would have read beyond the array. Atomic modes on byte views additionally require the offset to be aligned to the value's size.IndexOutOfBoundsException
What each mode costs
One thread writes a static field 50 million times in each mode. Best of 5 runs, a rough comparison on one machine; the point is the relative order, which follows from the hardware fences each mode needs.
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
public class ModeCost {
static int field;
static final VarHandle F;
static {
try {
F = MethodHandles.lookup().findStaticVarHandle(ModeCost.class, "field", int.class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
// One loop per mode, so each is compiled on its own
static void plain(int n) {
for (int i = 0; i < n; i++) {
F.set(i);
}
}
static void opaque(int n) {
for (int i = 0; i < n; i++) {
F.setOpaque(i);
}
}
static void release(int n) {
for (int i = 0; i < n; i++) {
F.setRelease(i);
}
}
static void volatileMode(int n) {
for (int i = 0; i < n; i++) {
F.setVolatile(i);
}
}
static void cas(int n) {
for (int i = 0; i < n; i++) {
F.compareAndSet(i, i + 1);
}
}
interface Loop {
void run(int n);
}
static void time(String name, Loop loop, int n) {
long best = Long.MAX_VALUE;
for (int r = 0; r < 5; r++) {
long t0 = System.nanoTime();
loop.run(n);
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-14s %5.2f ns per write%n", name, (double) best / n);
}
public static void main(String[] args) {
int n = 50000000;
System.out.println("one thread, 50,000,000 writes to a static field, best of 5:");
time("set (plain)", ModeCost::plain, n);
time("setOpaque", ModeCost::opaque, n);
time("setRelease", ModeCost::release, n);
time("setVolatile", ModeCost::volatileMode, n);
time("compareAndSet", ModeCost::cas, n);
}
}
Output (2-CPU x86-64 Linux machine, JDK 21, best of 5):
one thread, 50,000,000 writes to a static field, best of 5:
set (plain) 0.02 ns per write
setOpaque 0.13 ns per write
setRelease 0.13 ns per write
setVolatile 1.64 ns per write
compareAndSet 5.08 ns per write
- Plain writes in a loop cost almost nothing: the JIT is free to keep the value in a register and store only the final one.
- Opaque and release writes cost a fraction of a nanosecond. On x86, ordinary stores already have release semantics, so these only stop the compiler from merging or reordering them.
- Volatile writes were more than ten times as expensive as release writes, because each one is followed by a full fence that waits for the store buffer to drain. Compare-and-set was the most expensive, an atomic
each time.lock cmpxchg - On ARM processors the gaps between modes are different, since even acquire and release need barrier instructions there. Choose the mode for correctness first; the weaker modes are an optimization for code that has been measured and reviewed.
Choosing between VarHandle and the alternatives
| Need | Use |
|---|---|
| A single shared counter or reference in application code | |
| An atomic field in very many objects | A VarHandlevolatilestatic final |
| Atomic elements of a primitive array | MethodHandles.arrayElementVarHandleAtomicIntegerArray |
| Reading binary data with a byte order | byteArrayViewVarHandle |
| One-way publication from a writer to readers | setReleasegetAcquire |
| Flags written and read by several threads | Volatile mode, or a volatile |
Replacing sun.misc.Unsafe | VarHandles for fields and arrays; the |
See