VarHandle Atomic Field Access
Give a plain field atomic operations through a VarHandle: compareAndSet fails on stale expectations and getAndAdd returns the value it replaced.
Code
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
public class FlagFlipper {
private int state = 10;
public static void main(String[] args) throws ReflectiveOperationException {
VarHandle handle = MethodHandles.lookup()
.findVarHandle(FlagFlipper.class, "state", int.class);
FlagFlipper app = new FlagFlipper();
// 普通读:get 按调用点的返回类型适配
System.out.println("read: " + (int) handle.get(app));
// CAS:期望 10 换 20 → 成功
System.out.println("cas 10->20: " + handle.compareAndSet(app, 10, 20));
// CAS:期望还是 10 → 失败(当前已是 20)
System.out.println("cas 10->30: " + handle.compareAndSet(app, 10, 30));
// getAndAdd 返回旧值并原子累加
int before = (int) handle.getAndAdd(app, 5);
System.out.println("before add: " + before + " after: " + (int) handle.get(app));
// set 直接写
handle.set(app, 0);
System.out.println("reset: " + (int) handle.get(app));
}
}How it works
Count the class FlagFlipper as the entire surface area of VarHandle Atomic Field Access.
Putting it to use
Running the file prints labeled results such as read:, cas 10->20:, cas 10->30: — each operation’s effect is visible in the output.
Core lines
.findVarHandle(FlagFlipper.class, "state", int.class);
int before = (int) handle.getAndAdd(app, 5);
FlagFlipper app = new FlagFlipper();
Interactive Tools for This Topic
FAQ
- What does VarHandle Atomic Field Access print when run?
- Running the file directly is enough — expect labeled output lines such as `read:`, `cas 10->20:`, `cas 10->30:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.