Quick revision
The short answer
A VarHandle is a typed reference to a variable, such as a field, an array element or a location in off-heap memory, that supports a defined set of access modes, from plain reads and writes through acquire and release to volatile access and atomic operations. It was added in Java 9 as a supported replacement for the memory operations of sun.misc.Unsafe. For a compare-and-set we create one with MethodHandles.lookup().findVarHandle(Counter.class, "count", int.class), keep it in a static final field, and call COUNT.compareAndSet(this, expected, next) in a retry loop.
What to remember
In this answer, we saw that a VarHandle is a typed reference to a field, array element or off-heap location with defined access modes, added in Java 9 as the supported replacement for Unsafe's memory operations. We created one with findVarHandle, stored it in a static final field, and wrote a compare-and-set loop with getVolatile and compareAndSet. We also went through the access modes, from plain through opaque, acquire and release, and volatile to atomic updates, and saw that type checks turn Unsafe's silent mistakes into exceptions.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A VarHandle is a typed reference to a variable, such as a field, an array element or a location in off-heap memory, that supports a defined set of access modes, from plain reads and writes through acquire and release to volatile access and atomic operations. It was added in Java 9 as a supported replacement for the memory operations of sun.misc.Unsafe. For a compare-and-set we create one with MethodHandles.lookup().findVarHandle(Counter.class, "count", int.class), keep it in a static final field, and call COUNT.compareAndSet(this, expected, next) in a retry loop.
Why this question is asked
Lock-free code, the kind inside ConcurrentHashMap, thread pools and high-throughput queues, needs atomic operations directly on fields, without allocating an AtomicInteger for every one of them. For years the only fast way was sun.misc.Unsafe, an internal class that could also crash the JVM if misused. VarHandles gave us a safe, supported API with the same power, and the JDK's own concurrency classes now use them. Interviewers ask this to see whether we can write a correct compare-and-set loop and understand memory ordering. In this answer, we will recap compare-and-set and the older options, create a VarHandle, write the counter, look at the access modes, and compare setRelease with setVolatile.
1A Quick Recap of Compare-and-Set
A compare-and-set (CAS) is a single atomic CPU operation: set this variable to the new value, but only if it currently holds the expected value, and tell me whether it worked. If two threads try to change the same field at once, only one CAS succeeds; the other sees false, reads the fresh value and tries again. A loop of read, compute, CAS is how lock-free code updates shared state without blocking.
Before Java 9 we had three ways to do that on a field. AtomicInteger works, but it is a separate object, so a class with a million instances and one counter each needs a million extra objects. AtomicIntegerFieldUpdater works on a plain volatile int field without the extra object, but it uses reflection and performs access and type checks on each call, which makes it slower. sun.misc.Unsafe.compareAndSwapInt was fast but internal, unsupported and unchecked: a wrong offset silently corrupts memory.
2Creating a VarHandle for the Field
A VarHandle is created by a MethodHandles.Lookup, like a MethodHandle. We give it the class that declares the field, the field name and its type. The lookup checks access once, using the rights of the class that called lookup(), so a private field is fine when the lookup happens inside its own class. We store the result in a static final field, which lets the JIT treat it as a constant and compile each access into a single machine instruction.
There are matching factories for the other kinds of variable: findStaticVarHandle for static fields, MethodHandles.arrayElementVarHandle(int[].class) for array elements, and MethodHandles.byteArrayViewVarHandle for reading an int or a long out of a byte array. Off-heap memory gets its VarHandles from the Foreign Function and Memory API's layouts.
3Writing the Compare-and-Set Loop
Now we add the update methods. The loop reads the current value with volatile semantics, computes the next value, and tries the CAS. If another thread changed the value in between, the CAS returns false, and we go round again with the fresh value.
- Read count with getVolatilefor example 41
- Compute next42
- compareAndSet(this, 41, 42) succeeded?YesReturn 42NoAnother thread changed it: read again
3 steps in order. Play them, or step through them one at a time.
Notice the casts such as (int) COUNT.getVolatile(this). VarHandle methods are signature-polymorphic, like MethodHandle.invoke: the compiler uses the static types we write, including the cast, to build the call's type, which the VarHandle then checks against its own. The receiver this comes first because count is an instance field. For simple increments getAndAdd is enough, but the loop is the general tool: incrementUpTo shows a rule that needs to look at the current value first, which only a CAS loop can do atomically.
4The Access Modes
Every VarHandle supports a family of access modes, each with its own guarantee about ordering and visibility between threads. Choosing the weakest mode that is still correct can make code faster, because stronger modes need memory fences, instructions that stop the CPU and compiler from reordering memory operations around them.
| Mode | Methods | Guarantee |
|---|---|---|
| Plain | get, set | Like a normal field, no cross-thread ordering |
| Opaque | getOpaque, setOpaque | Not cached away; no ordering with other variables |
| Acquire / release | getAcquire, setRelease | Earlier writes visible to an acquiring reader |
| Volatile | getVolatile, setVolatile | Same as a volatile field, total order |
| Atomic update | compareAndSet, getAndAdd, getAndSet | Read-modify-write as one step |
Plain access behaves like an ordinary field. Opaque guarantees that the access really happens and is eventually seen, but gives no ordering with other variables. Acquire and release form a pair: a write with setRelease makes every earlier write visible to a thread that reads the same variable with getAcquire and sees that value. Volatile access is the strongest, a total order like the volatile keyword. The atomic modes, compareAndSet, compareAndExchange, weakCompareAndSet, getAndSet, getAndAdd and the bitwise getAndBitwiseOr family, are read-modify-write operations; compareAndSet and getAndAdd have volatile ordering, and weaker variants such as weakCompareAndSetRelease exist for expert code.
5Mistakes the Type Checks Catch
VarHandles are typed, and the mistakes that Unsafe would silently allow become exceptions. Asking for a field with the wrong type fails at lookup time, and calling an access mode with wrong argument types fails at the call.
So a typo or a refactoring that changes a field's type is caught on the first call instead of corrupting memory, which is the main reason the JDK could move its own code off Unsafe.
6Follow-up questions
When would you use setRelease instead of setVolatile?
When one thread publishes data that other threads read with getAcquire, and nothing else needs a full ordering. setRelease guarantees that all writes before it are visible to a reader that acquires the value, but unlike setVolatile it does not stop later reads from being reordered before the write. On x86 that means a plain store instead of a store followed by a full fence, which is noticeably cheaper in a hot loop. The classic example is a single-writer queue publishing its tail index after filling a slot; AtomicLong.lazySet was the older form of the same thing.
Why does the field still need to be volatile?
Strictly, VarHandle's access mode decides the ordering, not the keyword, so getVolatile works on a non-volatile field. But declaring it volatile means any ordinary read or write of the field elsewhere in the class is also safe, and it documents that the field is shared between threads. AtomicIntegerFieldUpdater, by contrast, requires the volatile keyword.
What is the difference between compareAndSet and weakCompareAndSet?
weakCompareAndSet may fail spuriously, returning false even when the value matched, which lets it map to cheaper instructions on some CPUs such as ARM. Inside a retry loop that is harmless, because we simply try again. compareAndSet only fails when the value really differs.
7Conclusion
In this answer, we saw that a VarHandle is a typed reference to a field, array element or off-heap location with defined access modes, added in Java 9 as the supported replacement for Unsafe's memory operations. We created one with findVarHandle, stored it in a static final field, and wrote a compare-and-set loop with getVolatile and compareAndSet. We also went through the access modes, from plain through opaque, acquire and release, and volatile to atomic updates, and saw that type checks turn Unsafe's silent mistakes into exceptions.
Open with
A VarHandle is a typed reference to a variable: an instance or static field, an array element, or off-heap memory. It supports a set of access modes with defined memory ordering.
Then, if they want more
It was added in Java 9 so that the JDK and libraries had a supported, safe replacement for sun.misc.Unsafe's memory operations; AtomicIntegerFieldUpdater existed but is slower because of its per-call reflective checks, and AtomicInteger costs an extra object per field.
For a counter, I'd declare a private volatile int count, and a private static final VarHandle COUNT created in a static initializer with MethodHandles.lookup().findVarHandle(Counter.class, "count", int.class). Keeping it static final lets the JIT compile each access to a single instruction. Then the CAS loop: read current with COUNT.getVolatile(this), compute next, and loop while COUNT.compareAndSet(this, current, next) returns false.
For a plain increment getAndAdd is simpler, but the loop handles rules like increment up to a maximum. The access modes go from plain get and set, through opaque, getAcquire and setRelease, to getVolatile and setVolatile, plus atomic operations like compareAndSet, compareAndExchange and getAndAdd.
I'd use setRelease when a single writer publishes data to readers using getAcquire; it's cheaper than a volatile write because it doesn't need a full fence.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What is a VarHandle and why was it added in Java 9? Show how you would perform a...": https://scrivio-interview-library.netlify.app/java/reflection-and-method-handles/cc9d828ad3/