AtomicIntegerFieldUpdater 能让一个普通 volatile 字段拥有 CAS 操作,而不必每个对象多挂一个 AtomicInteger。它有哪些限制?违反时抛什么?省多少内存?这篇逐项触发。
volatile int → 创建成功
非 volatile int → IllegalArgumentException: Must be volatile type
private volatile int(在 Main 内部类里) → 创建成功
static volatile int → IllegalArgumentException: null
final int → IllegalArgumentException: Must be volatile type
volatile long 用 IntegerUpdater → IllegalArgumentException: Must be integer type
volatile Integer 用 IntegerUpdater → IllegalArgumentException: Must be integer type
不存在的字段名 → RuntimeException: java.lang.NoSuchFieldException: zzz
volatile long 用 LongUpdater → 创建成功
volatile String 用 ReferenceUpdater → 创建成功
ReferenceUpdater 声明的类型写成 Object → ClassCastException: null
ReferenceUpdater 字段类型 String 写成 CharSequence → ClassCastException: null
null 对象 .get(null) → ClassCastException: null
incrementAndGet / compareAndSet / getAndAdd:1 true 10 最终 n=15
传入了不是 Ok 的对象 → ClassCastException: null 在 q.Other 里为 p.Target.pub → 创建成功
在 q.Other 里为 p.Target.pkg → RuntimeException: java.lang.IllegalAccessException: class q.Other cannot access a member of class p.Target with package access
在 q.Other 里为 p.Target.prot → RuntimeException: java.lang.IllegalAccessException: class q.Other cannot access a member of class p.Target with modifiers "protected volatile"
在 q.Other 里为 p.Target.priv → RuntimeException: java.lang.IllegalAccessException: class q.Other cannot access a member of class p.Target with modifiers "private volatile"
子类访问 protected 字段:
子类 Sub 上:RuntimeException: java.lang.NoSuchFieldException: prot
子类里为 p.Target 创建 updater:成功 100 万个对象的堆增量:带 AtomicInteger 字段 34.6 MB(每个对象约 34 字节);带 volatile int + updater 20.0 MB(每个约 20 字节)
(保持引用:1000000,1000000)