skip to content

What is a VarHandle, and why was it introduced as a replacement for sun.misc.Unsafe?

level: seniorimportance: should knowfreq 38%

answer

  1. java.lang.invoke, Java 9, JEP 193
  2. Typed handle to field / array element / buffer location
  3. Field handles via MethodHandles.Lookup (access-checked)
  4. Safe + supported + JIT-fast replacement for sun.misc.Unsafe
  5. Access modes: plain / opaque / acquire-release / volatile, plus CAS

basics

~20 s

A VarHandle (added in Java 9) is a typed reference to a variable — a field, array element, or off-heap location — that lets you read and write it with different levels of atomicity and memory ordering, including CAS. It is the safe, supported, standard replacement for the internal, unsupported sun.misc.Unsafe.

solid answer

~50 s

A VarHandle, from java.lang.invoke, is a strongly-typed handle to a variable (an instance/static field, an array element, or a buffer location); field handles come from a MethodHandles.Lookup, array handles from static MethodHandles factories. Through it you perform memory operations at a chosen access mode: plain get/set, opaque, acquire/release, and full volatile, plus atomic operations like compareAndSet, getAndAdd, and weakCompareAndSet. It was introduced in Java 9 to give application and library authors a standard, type-checked, JIT-optimized API for the low-level atomic and ordered access that previously was only possible through sun.misc.Unsafe — an internal, unsupported, type-unsafe class that could corrupt memory, which Java 9's module system left accessible only because no supported replacement existed yet. VarHandle was designed to perform the same as or close to Unsafe when held in a static final field. Since JDK 23 Unsafe's memory-access methods are deprecated for removal; on JDK 25 and 27 their first use warns.

go deeper

for a junior

Should at least recognize VarHandle as a low-level concurrency API in newer Java; deep usage is not expected.

for a middle

Can say VarHandle gives atomic/ordered access to fields and arrays and replaced the internal Unsafe, and roughly how you obtain one.

for a senior

Explains the Unsafe problems (internal, type-unsafe, unsupported, its memory-access methods deprecated for removal since JDK 23), how VarHandle is type-checked, JIT-intrinsified, obtained via a Lookup for fields or a static factory for arrays, and lists the access modes.

for a principal

Frames the platform motivation (JPMS encapsulating internals while Unsafe waited for a replacement, then the phased removal of its memory-access methods from JDK 23), the near-Unsafe performance goal, and which atomic classes now sit on VarHandle and which still do not.

## Background: why this API exists To build lock-free data structures and high-performance concurrency primitives, you need low-level control over memory: the ability to perform a **compare-and-swap (CAS)** on a field, to read/write with specific **memory ordering** (controlling when one thread's writes become visible to another), and to do this on fields and array elements directly. For years the JDK's own `Atomic*` classes obtained this power from an internal class, **`sun.misc.Unsafe`**. ### The trouble with sun.misc.Unsafe `sun.misc.Unsafe` is exactly what its name says: a backdoor of raw, unchecked memory operations. - It is **internal and unsupported** — not part of the public Java SE API, with no compatibility guarantee. - It is **type-unsafe**: you pass raw field offsets and object references, and a mistake (wrong offset, wrong type) can corrupt the heap or crash the JVM, because no checks protect you. - It was nonetheless **widely used** by libraries (high-performance queues, serialization frameworks, off-heap stores) because nothing else offered the same capability. - The **Java Platform Module System (Java 9)** encapsulated most internal APIs, but JEP 260 left `sun.misc.Unsafe` accessible, in the `jdk.unsupported` module, because no supported replacement existed yet, and pointed to variable handles for much of its functionality. The JDK needed a **public, supported, safe** replacement that did not sacrifice performance. That replacement is `VarHandle`. ## What a VarHandle is A **`VarHandle`** (in `java.lang.invoke`, JEP 193, Java 9) is a **typed reference to a variable**. "Variable" here is general: it can be - an **instance field**, - a **static field**, - an **array element**, - or a location in an off-heap buffer (e.g. via `MethodHandles.byteBufferViewVarHandle`). It is the variable-access analogue of a `MethodHandle` (which is a typed reference to a method). You don't read/write the variable directly through the language; you go through the handle, which carries the variable's type and coordinate types (e.g. "this VarHandle accesses an `int` field of receiver type `Node`"). ### How you get one For a field you obtain a VarHandle via a **`MethodHandles.Lookup`**, which enforces access control — you can only get a handle to a field you are allowed to access: ```java class Counter { private volatile int value; private static final VarHandle VALUE; static { try { VALUE = MethodHandles.lookup() .findVarHandle(Counter.class, "value", int.class); } catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); } } } ``` For arrays you use the static factory `MethodHandles.arrayElementVarHandle(int[].class)`, which needs no Lookup, and the access methods then take the array plus the index as coordinates. ## What it lets you do: access modes The defining feature of VarHandle is that **every operation names an access mode** that selects atomicity and memory-ordering strength. The four ordering levels, from weakest to strongest, are: - **plain** (`get`/`set`) — like a normal field read/write, no extra ordering. - **opaque** (`getOpaque`/`setOpaque`) — atomic and coherent per-variable, but no cross-variable ordering. - **acquire/release** (`getAcquire`/`setRelease`) — an acquire read and the accesses after it are ordered after a matching release write and the accesses before it; one-directional ordering for cheap publication. - **volatile** (`getVolatile`/`setVolatile`) — full volatile semantics (the strongest, bidirectional ordering). On top of those it offers **atomic update** operations: `compareAndSet`, `compareAndExchange`, `weakCompareAndSet` (may fail spuriously, for retry loops), `getAndSet`, `getAndAdd`, `getAndBitwiseOr`, etc. (The access-mode detail is its own topic; the key point here is that one handle exposes the full ladder, where `volatile`/CAS used to be all you could express.) ## Why it is better than Unsafe 1. **Type-safe and access-checked** — the Lookup enforces visibility, and operations are checked against the variable's declared type, so you cannot silently corrupt memory the way a raw offset in Unsafe could. 2. **Supported and standard** — public Java SE API with a compatibility contract, unlike the internal `sun.misc.Unsafe`. 3. **Close to Unsafe's speed** — JEP 193's goal is performance "the same as or similar to" the equivalent Unsafe operations, with almost identical generated code apart from certain safety checks that cannot be folded away; the JEP asks for the handle to sit in a `static final` field so the JIT can fold away its method-signature and argument-cast checks. 4. **More expressive** — the explicit ladder of access modes lets you choose exactly the ordering strength you need (e.g. cheap acquire/release publication) instead of paying for full `volatile` everywhere. 5. **Module-system friendly** — it is the sanctioned path so libraries can stop depending on unsupported internals. Inside the JDK, `AtomicReference`, `AtomicBoolean`, the `Atomic*Array` classes and `LongAdder`'s cells use VarHandles, while `AtomicInteger`, `AtomicLong` and the three field updaters still use the JDK-internal `jdk.internal.misc.Unsafe`; `AtomicInteger`'s source notes that VarHandles hit "unresolved cyclic startup dependencies" there. ## Where sun.misc.Unsafe stands now - **JDK 23** deprecated its memory-access methods for removal (JEP 471), naming `VarHandle` for on-heap memory and the Foreign Function & Memory API's `MemorySegment` (final in JDK 22) for off-heap memory. - **JDK 24** made the first call to one of them print a warning by default (JEP 498). On JDK 25 and 27 the call still works after the warning, and `--sun-misc-unsafe-memory-access=deny` makes it throw `UnsupportedOperationException`; JEP 471 plans that as the default in a later phase. ## Summary A `VarHandle` is a typed, access-controlled handle to a field/array element/buffer location offering the full ladder of memory-access modes and atomic operations. Java 9 introduced it (JEP 193) as the safe, supported, module-friendly replacement for the internal and dangerous `sun.misc.Unsafe`, designed to perform close to it; Unsafe's memory-access methods have been on their way out since JDK 23, and VarHandle already underpins several of the atomic classes.

  • How do you obtain a VarHandle for a private field, and what enforces that you are allowed to?
    You use a MethodHandles.Lookup with sufficient access (e.g. MethodHandles.lookup() from inside the declaring class) and call findVarHandle(owner, name, type). The Lookup's access rights enforce visibility, so you cannot get a handle to a field you could not legally access.
  • Does VarHandle replace reflection for ordinary field reads/writes?
    It can read/write fields, but its purpose is low-level atomic/ordered access, not general reflection. JEP 193 asks for VarHandles to be held in static final fields so the JIT can fold away their signature and cast checks; it is a concurrency tool rather than a general Field replacement.

  • Calling sun.misc.Unsafe a public/supported API — it is internal and unsupported
  • Assuming VarHandle must be slower than Unsafe — held in a static final field it compiles to nearly the same code
  • Thinking VarHandle is just reflection — it is JIT-intrinsified, not reflective dispatch per call
  • Saying VarHandle only does volatile/CAS — it exposes a full ladder of ordering modes
  • Confusing VarHandle (variable access) with MethodHandle (method access)

VarHandle
Java 9

Assumes JDK 27 and checks 25: on both, sun.misc.Unsafe's memory-access methods are deprecated for removal (JDK 23) and warn on first use by default (JDK 24); JEP 471 plans exceptions by default for a later release.

context