CKTIS / Java
VarHandle: acquire-release access and atomic CAS
VarHandle provides typed access to variables with selectable memory ordering. Learn getAcquire, setRelease, and compareAndSet, and distinguish data publication from an atomic update.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
VarHandle h = MethodHandles.lookup().findVarHandle(Owner.class, "field", int.class);
int value = (int) h.getAcquire(owner);
h.setRelease(owner, newValue);
boolean changed = h.compareAndSet(owner, expectedValue, newValue);java.lang.invoke.VarHandle represents access to a variable. For an instance field, the first argument is the object containing the field. A handle returned by findVarHandle uses adapting invocation by default: compatible call-site types can be converted under MethodHandle.asType rules. The call-site type must exactly match the access mode type only with exact invocation behavior (for example, after using withInvokeExactBehavior).
VarHandle.setRelease prevents earlier reads and writes from moving after the release write. VarHandle.getAcquire prevents later reads and writes from moving before the acquire read. When acquire reads a matching release write, it also makes the publishing thread's earlier writes visible. Merely using both methods does not guarantee reading the new value.
VarHandle.compareAndSet atomically compares the current value with the expected value and writes the replacement only on a match. For float and double, it compares the raw bit representations of the values; for other types, it uses == semantics. It therefore distinguishes positive and negative zero even though floating-point == treats them as equal. It returns a boolean; the read has volatile semantics, as does a successful write. Separate getAcquire and setRelease calls do not form an atomic update.
Incorrect types can cause WrongMethodTypeException, and an unsupported mode causes UnsupportedOperationException. The single-threaded example demonstrates deterministic results, not the correctness of concurrent publication.
Examples
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
public class Main {
private int state;
public static void main(String[] args) throws ReflectiveOperationException {
VarHandle stateHandle = MethodHandles.lookup()
.findVarHandle(Main.class, "state", int.class);
Main owner = new Main();
stateHandle.setRelease(owner, 1);
int observed = (int) stateHandle.getAcquire(owner);
boolean first = stateHandle.compareAndSet(owner, 1, 2);
boolean second = stateHandle.compareAndSet(owner, 1, 3);
System.out.println(observed);
System.out.println(first);
System.out.println(second);
System.out.println((int) stateHandle.getAcquire(owner));
}
}Result
1 true false 2
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.