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.VarHandle (Java 9, JEP 193) points at a variable rather than holding a value: an instance field, a static field, an element of an array, or an int or long stored at some offset inside a byte[] or ByteBuffer. Through the handle you can read and write the variable in several access modes, from plain to fully volatile, and perform atomic read-modify-write operations such as compare-and-set. It is obtained from a MethodHandles.Lookup, so normal access checks apply, and is usually stored in a static final field so the JIT can compile each call down to the matching machine instruction.

Before Java 9, libraries reached for sun.misc.Unsafe for the same abilities, with no type or bounds checks. VarHandles give the same performance safely, and the JDK is retiring Unsafe's memory access methods: they were deprecated for removal in Java 23 (JEP 471) and warn when used from Java 24 (JEP 498). Like method handles, VarHandle methods are signature polymorphic: the types at the call site, including casts on results, must match the variable's type exactly.

VarHandle access modes, from weakest to strongest
ModeMethodsGuaranteesBest for
Plainget, setLike a normal field: no ordering or visibility promises between threadsSingle-threaded access to the same variable
OpaquegetOpaque, setOpaqueThe access really happens and is eventually visible; no ordering with other variablesProgress flags and counters read approximately
Acquire / releasegetAcquire, setReleaseWrites before a release are visible to a thread whose acquire reads that valuePublishing data from one thread to another
VolatilegetVolatile, setVolatileSame as a volatile field: one total order of all volatile accessesWhen in doubt; flags read and written by many threads
Atomic updatescompareAndSet, compareAndExchange, getAndAdd, getAndSet, getAndBitwiseOr and othersAtomic read-modify-write, volatile ordering unless the name says otherwiseLock-free counters and state machines

Most application code should use the atomic classes, which are simpler. VarHandles pay off in libraries that need an atomic field in many objects, atomic array elements without wrapper objects, or weaker and cheaper ordering. The VarHandle programs were run on JDK 21.

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 ++ for comparison. They also record a running maximum with a hand-written compare-and-set loop.

Java
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:

Output
expected:            1000000
VarHandle getAndAdd: 1000000
plain ++:            557770 (varies; lost some: true)
max seen:            999999
1L for an int field: WrongMethodTypeException
  • getAndAdd reached exactly 1,000,000; the plain ++ lost updates, a different number on every run. The VarHandle made the field atomic without turning it into an AtomicInteger object.
  • recordMax 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.
  • Passing 1L for an int field threw WrongMethodTypeException. The check happens at the call, because the handle's methods take Object... in source code but are linked to the exact types used.
  • Two variants of compare-and-set are worth knowing. compareAndExchange returns the value it found instead of a boolean, which saves a separate read when the loop has to retry. weakCompareAndSet 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.
  • The handle is looked up once, in a static initializer, with findVarHandle(class, name, type). Looking it up per call would be slow and would defeat the JIT.

Publishing data with release and acquire

A producer writes a plain field and then sets a flag with setRelease; a consumer spins on getAcquire and reads the field once it sees the flag. Neither field is volatile. The second part asks a VarHandle on a final field which modes it supports.

Java
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:

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 data = 42. 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 a volatile flag, with a cheaper write on most CPUs.
  • The handle on the final field supports the read modes but not SET or COMPARE_AND_SET. isAccessModeSupported lets generic code check before calling.
  • 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 Java Memory Model page is run twice: thread A writes x and reads y, thread B writes y and reads x, a million times, first with release writes and acquire reads, then with volatile accesses. The question is how often both threads read 0.

Java
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):

Output
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[], and one that reads and writes ints at byte offsets inside a byte[], in a chosen byte order.

Java
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:

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 int[] atomically, 250,000 times each, without an AtomicIntegerArray. The handle takes the array and the index as its first arguments.
  • The byte view wrote 0x0A0B0C0D 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 gave 0x0D0C0B0A, the classic symptom of a byte-order mistake when parsing binary data.
  • Offset 6 would need bytes 6 to 9 of an 8-byte array and threw IndexOutOfBoundsException, 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.

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.

Java
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):

Output
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 lock cmpxchg each time.
  • 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

Which tool for atomic or ordered access
NeedUse
A single shared counter or reference in application codeAtomicInteger, AtomicLong, AtomicReference
An atomic field in very many objectsA VarHandle on a volatile field, in a static final
Atomic elements of a primitive arrayMethodHandles.arrayElementVarHandle, or AtomicIntegerArray
Reading binary data with a byte orderbyteArrayViewVarHandle, or ByteBuffer
One-way publication from a writer to readerssetRelease and getAcquire
Flags written and read by several threadsVolatile mode, or a volatile field
Replacing sun.misc.UnsafeVarHandles for fields and arrays; the Foreign Memory API for off-heap memory

See method handles for the lookup machinery VarHandles share, and synchronized and volatile for the language-level equivalents.