import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; /** AFTER: the same field with a VarHandle (JEP 193, JDK 9). No Unsafe anywhere. */ public class VarHandleFieldCounter implements FieldCounter { private static final VarHandle VALUE; static { try { VALUE = MethodHandles.lookup().findVarHandle(VarHandleFieldCounter.class, "value", long.class); } catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); } } private volatile long value; public long get() { return value; } public void set(long v) { value = v; } public boolean cas(long expect, long update) { return VALUE.compareAndSet(this, expect, update); } public long getAndAdd(long delta) { return (long) VALUE.getAndAdd(this, delta); } }