CKTIS / Java
VarHandle: acquire reads, release writes, and atomic CAS
In Java SE 21, get a handle to a plain `int` field, choose memory ordering for reads and writes, and conditionally update the value in one atomic step.
Version: Java SE 21
Syntax
VarHandle handle = MethodHandles.lookup().findVarHandle(VarHandleDemo.class, "state", int.class);
int observed = (int) handle.getAcquire(demo);
handle.setRelease(demo, newValue);
boolean updated = handle.compareAndSet(demo, expectedValue, newValue);In java.lang.invoke, MethodHandles.lookup() returns a lookup with the calling class's access privileges. MethodHandles.Lookup.findVarHandle takes the receiver class where the lookup starts, the field name, and the exact type of the instance field (int.class, not Integer.class). The receiver class can be a subclass that inherits the field, provided the lookup has access to it. The handle is not bound to an object: pass the instance as the first argument to each operation. For a static field, use findStaticVarHandle; its operations take no instance.
Access is checked when the handle is created. No field with the given name and type means NoSuchFieldException; denied access or finding a static field with findVarHandle means IllegalAccessException. Don't give untrusted code a handle to a private field: it can use the handle without another field access check.
VarHandle.getAcquire/setRelease/compareAndSet names three separate methods. setRelease(obj, value) writes with release ordering, and (int) handle.getAcquire(obj) reads with acquire ordering. If the acquire read observes the release write to the same field, memory accesses before the write are ordered before accesses after the read. The read does not wait for a newer value. The handle's mode supplies the ordering: the plain int field need not be volatile, and reading it directly does not have acquire semantics.
compareAndSet(obj, expected, update) atomically compares the current int using == and, on a match, writes the new value and returns true. On a mismatch it returns false without writing. The read and, on success, the write have volatile semantics. Access methods are signature-polymorphic: despite Object... in the declarations, call-site types, including the (int) result cast, shape the call descriptor. An incompatible type can cause WrongMethodTypeException, a failed reference cast can cause ClassCastException, and an unsupported mode (such as writing a final field) throws UnsupportedOperationException.
Examples
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
public class VarHandleDemo {
private int state;
public static void main(String[] args) throws ReflectiveOperationException {
VarHandle stateHandle = MethodHandles.lookup()
.findVarHandle(VarHandleDemo.class, "state", int.class);
VarHandleDemo demo = new VarHandleDemo();
stateHandle.setRelease(demo, 1);
int observed = (int) stateHandle.getAcquire(demo);
boolean updated = stateHandle.compareAndSet(demo, observed, 2);
boolean staleUpdate = stateHandle.compareAndSet(demo, 1, 3);
int finalState = (int) stateHandle.getAcquire(demo);
System.out.println("observed=" + observed);
System.out.println("updated=" + updated);
System.out.println("staleUpdate=" + staleUpdate);
System.out.println("finalState=" + finalState);
}
}Result
observed=1 updated=true staleUpdate=false finalState=2
On one thread, the program writes `1`, reads `1`, changes it to `2` with CAS, and rejects the second attempt with stale expected value `1`. The output demonstrates the calls, not visibility between threads.
Related lessons
- Java · Lesson 57 · Advanced · Version: 2