AtomicIntegerFieldUpdater访问权限问题

AtomicIntegerFieldUpdater所要修改的变量必须可在当前类访问,否则将抛出异常

java.lang.RuntimeException: java.lang.IllegalAccessException: Class XXXXX can not access a member of class XXX with modifiers “private volatile”

原因在AtomicIntegerFieldUpdaterImpl构造函数之中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
final Field field;
final int modifiers;
try {
field = AccessController.doPrivileged(
new PrivilegedExceptionAction<Field>() {
public Field run() throws NoSuchFieldException {
return tclass.getDeclaredField(fieldName);
}
});
modifiers = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifiers);
ClassLoader cl = tclass.getClassLoader();
ClassLoader ccl = caller.getClassLoader();
if ((ccl != null) && (ccl != cl) &&
((cl == null) || !isAncestor(cl, ccl))) {
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
}
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae.getException());
} catch (Exception ex) {
throw new RuntimeException(ex);
}

代码中的第10行直接获取Modifiers,并没有抑制JVM的访问权限检查

将成员变量修饰符换掉即可