Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Replace this Unsafe-based compare-and-set on a field with a VarHandle, and explain what you gain:

Java
private static final long STATE_OFFSET = UNSAFE.objectFieldOffset(Task.class.getDeclaredField("state"));
boolean tryStart() {
return UNSAFE.compareAndSwapInt(this, STATE_OFFSET, 0, 1);
}

We replace the field offset with a VarHandle created once in a static initialiser, private static final VarHandle STATE = MethodHandles.lookup().findVarHandle(Task.class, "state", int.class), with the checked exceptions wrapped, and write tryStart() as return STATE.compareAndSet(this, 0, 1); with the field declared volatile int state. We gain a supported API with type checking and access control that the JIT compiles to the same instruction, plus a full set of access modes, and for simple cases AtomicInteger or AtomicIntegerFieldUpdater are enough.

Why this question is asked

This snippet is a classic piece of older high-performance Java: a lock-free state transition done with Unsafe. Code like this now produces warnings on recent JDKs and will stop working when the memory-access methods are removed. Interviewers ask us to rewrite it because the change looks mechanical but hides real details: the static initialiser, the volatile field, the types, and what the new API protects us from. In this answer, we will read what the original code does, write the VarHandle version step by step, see what goes wrong when we make a mistake in each version, look at the access modes VarHandle offers, and finish with the simpler alternatives.

1What the Original Code Does

The goal is a one-time transition: a Task starts in state 0, and exactly one thread may move it to state 1, even if many threads call tryStart() at the same moment. Compare-and-set, often shortened to CAS, does this atomically: it changes the value to 1 only if it is currently 0, and returns whether it did.

The Unsafe version works with raw memory. objectFieldOffset asks where the state field sits inside a Task object, as a number of bytes from the start of the object. compareAndSwapInt then performs the CAS on the four bytes at this object plus that offset. The JIT turns it into a single atomic instruction, lock cmpxchg on x64.

Java
private static final Unsafe UNSAFE = ...; // taken through reflection
private static final long STATE_OFFSET;
static {
try { STATE_OFFSET = UNSAFE.objectFieldOffset(Task.class.getDeclaredField("state")); }
catch (NoSuchFieldException e) { throw new Error(e); }
}
private int state; // 0 = new, 1 = started
boolean tryStart() { return UNSAFE.compareAndSwapInt(this, STATE_OFFSET, 0, 1); }
// Java 24+: WARNING: A terminally deprecated method in sun.misc.Unsafe has been called

Notice that the offset is just a long. Nothing ties it to the int type or to the Task class; the code trusts that we use it correctly.

2The VarHandle Version

A VarHandle is a typed reference to a variable, here the state field of Task. We create it once, in a static field, using a lookup object that has access to the private field because it is created inside the Task class.

Java
final class Task {
private volatile int state; // 0 = new, 1 = started
private static final VarHandle STATE;
static {
try {
STATE = MethodHandles.lookup().findVarHandle(Task.class, "state", int.class);
} catch (ReflectiveOperationException e) { // NoSuchFieldException, IllegalAccessException
throw new ExceptionInInitializerError(e);
}
}
boolean tryStart() { return STATE.compareAndSet(this, 0, 1); }
boolean isStarted() { return state == 1; } // a plain read of the volatile field
}
Task t = new Task();
System.out.println(t.tryStart()); // true: 0 -> 1
System.out.println(t.tryStart()); // false: already 1
System.out.println(t.isStarted()); // true
Step throughTwo threads race to start the same task
Thread ATask.stateThread B
STATE.compareAndSet(task, 0, 1)
true: state is now 1
STATE.compareAndSet(task, 0, 1)
false: state is 1, not 0

4 messages in order. Play them, or step through them one at a time.

Exactly one caller wins, without a lock.

findVarHandle throws checked exceptions, so it must live in a static block that wraps them; a static final field cannot be initialised with a call that throws checked exceptions directly. If the field is renamed, the class fails to initialise immediately with a clear error, rather than later in some code path.

The field is declared volatile. compareAndSet itself always has volatile memory semantics, whatever the declaration, but other code reads the field too, such as isStarted(). Declaring it volatile makes those plain reads see the latest value written by another thread. It also documents to the reader that this field is shared between threads.

3What Each Version Does With a Mistake

The real gain shows up when someone makes a mistake. Suppose a later change passes long values, or uses the long CAS method by habit.

Java
// Unsafe: compiles and runs, and writes 8 bytes into a 4-byte field
UNSAFE.compareAndSwapLong(this, STATE_OFFSET, 0L, 1L); // corrupts the neighbouring field, no error
// VarHandle: the handle knows the variable is an int in a Task
STATE.compareAndSet(this, 0L, 1L); // WrongMethodTypeException at run time
STATE.compareAndSet(otherObject, 0, 1); // ClassCastException: not a Task
// Lookup respects access control
MethodHandles.lookup().findVarHandle(Order.class, "secret", int.class);
// IllegalAccessException if Order's private field is not accessible from here

So Unsafe fails silently and dangerously, while VarHandle fails loudly with a clear exception. That is the meaning of type checking and access control here: the handle remembers the class and the type of the variable, and the lookup only grants access that ordinary Java rules would allow. None of it slows down the hot path; the JIT inlines the static final VarHandle and emits the same lock cmpxchg instruction as before.

4The Access Modes VarHandle Offers

Unsafe had a scattered set of methods for different memory orderings. VarHandle organises them into access modes, from weakest to strongest. Plain get and set behave like a normal field access. Opaque access guarantees the value is really read or written, not cached or removed by the compiler, but gives no ordering with other variables. Acquire and release modes, getAcquire and setRelease, give one-way ordering, which is enough for publishing data from one thread to another. Volatile mode, getVolatile and setVolatile, gives full sequential consistency.

On top of these come the atomic read-modify-write operations: compareAndSet, compareAndExchange, which returns the value it found, weakCompareAndSet, which may fail spuriously and suits retry loops, and getAndAdd, getAndSet and bitwise variants. There are also static fence methods, fullFence, acquireFence and releaseFence, for the rare cases that need them.

VarHandle access modes
ModeExample methodsTypical use
Plainget, setsingle-threaded or already-synchronised access
OpaquegetOpaque, setOpaqueprogress flags polled in a loop
Acquire/ReleasegetAcquire, setReleasepublishing data to another thread
VolatilegetVolatile, setVolatilesame as a volatile field
Atomic updatecompareAndSet, getAndAdd, getAndSetcounters, state machines, lock-free queues

5When Something Simpler Is Enough

VarHandle is the right tool when we want the atomic field inside our own object, with no extra allocation per object. If that does not matter, simpler classes from java.util.concurrent.atomic do the same job. An AtomicInteger field gives compareAndSet with no setup code, at the cost of one extra small object per Task. AtomicIntegerFieldUpdater works on a volatile int field directly like VarHandle, with a little more checking overhead on each call.

Java
private final AtomicInteger state = new AtomicInteger(); // extra object per Task
boolean tryStart() { return state.compareAndSet(0, 1); }
private static final AtomicIntegerFieldUpdater<Task> UPDATER =
AtomicIntegerFieldUpdater.newUpdater(Task.class, "state"); // field must be volatile int
boolean tryStart2() { return UPDATER.compareAndSet(this, 0, 1); }

For a class with a few thousand instances, AtomicInteger is the most readable choice. For a class with millions of instances, such as nodes in a concurrent data structure, the VarHandle on a plain volatile field saves memory, which is why the JDK's own concurrent classes use it.

6Follow-up questions

Why must the VarHandle be static final?

Because the JIT treats a static final VarHandle as a constant and can inline the access into a single instruction. A VarHandle held in an instance field or a local variable still works, but the JIT cannot specialise it as well, and the call becomes noticeably slower.

What is the difference between compareAndSet and weakCompareAndSet?

compareAndSet only fails when the current value is not the expected one. weakCompareAndSet may also fail spuriously even when the value matches, which lets it compile to cheaper instructions on some CPUs such as ARM. It is fine inside a retry loop, but for a one-shot transition like tryStart, compareAndSet is the correct choice.

Can a VarHandle access a field in another class?

Yes, if the lookup has access. For a private field in another class we use MethodHandles.privateLookupIn(Target.class, MethodHandles.lookup()), which works only when the target's module opens that package to ours. This keeps module encapsulation intact, unlike Unsafe offsets.

7Conclusion

In this answer, we replaced an Unsafe compare-and-swap with a VarHandle. We created the handle once in a static initialiser with findVarHandle, wrapping its checked exceptions, declared the field volatile int, and wrote tryStart() as STATE.compareAndSet(this, 0, 1). The JIT emits the same atomic instruction, but VarHandle is supported, checks the type and class of every access, and respects access control, so mistakes fail loudly instead of corrupting memory. It also offers access modes from plain to volatile and atomic operations such as getAndAdd, while AtomicInteger or AtomicIntegerFieldUpdater are simpler choices when per-object overhead does not matter.

What to say in the interviewAbout 70 seconds aloud

Open with

I would declare the field as private volatile int state, and create a static final VarHandle in a static initialiser: MethodHandles.lookup().findVarHandle(Task.class, "state", int.class), catching ReflectiveOperationException and rethrowing it as ExceptionInInitializerError, because findVarHandle throws checked exceptions.

Then, if they want more

Then tryStart becomes return STATE.compareAndSet(this, 0, 1). compareAndSet has volatile semantics on its own, but declaring the field volatile makes ordinary reads elsewhere see the latest value and tells readers it is shared. What we gain: VarHandle is a supported API, while those Unsafe methods are deprecated for removal and already warn on Java 24.

It is type-checked, so passing longs gives a WrongMethodTypeException instead of silently writing eight bytes into a four-byte field, and the lookup respects access control and modules. Performance is the same, because the JIT inlines a static final VarHandle into the same lock cmpxchg instruction.

It also gives a clean set of access modes, plain, opaque, acquire and release, and volatile, plus getAndAdd, getAndSet and compareAndExchange. If I do not care about one extra object per instance, AtomicInteger is simpler, and AtomicIntegerFieldUpdater is another option on a volatile int field.

About this answer

Last updated
12 November 2026
Versions it names
Java 24
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.
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 "Replace this Unsafe-based compare-and-set on a field with a VarHandle, and explain what...": https://scrivio-interview-library.netlify.app/java/foreign-memory-and-native/116e746b24/