What is VarHandle and why did it replace sun.misc.Unsafe? — Cracked Java
// Concurrency & Multithreading · Atomics & Compare-And-Swap
SeniorTheory

What is VarHandle and why did it replace sun.misc.Unsafe?

VarHandle (Java 9, JEP 193) is a typed, supported reference to a variable — a field, array element, or off-heap location — that exposes atomic and ordered access modes (CAS, get/set with acquire/release/volatile/plain semantics). It replaced sun.misc.Unsafe because Unsafe was an unofficial, type-unsafe, memory-corrupting internal API that everyone nonetheless depended on.

Why Unsafe had to go

sun.misc.Unsafe gave low-level CAS, fences, and direct memory access — the engine under every Atomic* class. But it was never a public API: it bypassed access control, took raw field offsets (a wrong offset corrupts the heap or crashes the JVM), and had no type checking. With the module system (JPMS) Java needed to lock down internal APIs, but it couldn't break the entire ecosystem that leaned on Unsafe. VarHandle is the sanctioned, type-safe replacement.

What VarHandle gives you

A VarHandle is obtained from MethodHandles.lookup(), so access control is respected. It offers a full menu of access modes matching the JMM:

class Counter {
    private volatile long value;   // VarHandle requires the right declared field

    private static final VarHandle VALUE;
    static {
        try {
            VALUE = MethodHandles.lookup()
                .findVarHandle(Counter.class, "value", long.class);
        } catch (ReflectiveOperationException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    void increment() {
        long prev;
        do {
            prev = (long) VALUE.getVolatile(this);
        } while (!VALUE.compareAndSet(this, prev, prev + 1));  // lock-free CAS
    }
}

The access modes span the memory model precisely:

  • Plainget/set, no ordering (fastest).
  • Opaque — bitwise atomic, no ordering with other variables.
  • Acquire/ReleasegetAcquire/setRelease, one-directional fences.
  • VolatilegetVolatile/setVolatile, full ordering.
  • Atomic RMWcompareAndSet, compareAndExchange, getAndAdd, getAndSet, plus weakCompareAndSet (may spuriously fail, cheaper on LL/SC hardware).

Mark your status