java.util.concurrent.atomic
包中提供了一些原子操作类, 可分为4中类型:
- 原子更新基本类型类
- 原子更新引用类型类
- 原子更新数组(元素)类
- 原子更新字段类
1. 原子更新基本类型类
AtomicBoolean
类
AtomicInteger
类
AtomicLong
类
2. 原子更新引用类型类
AtomicReference
类
AtomicMarkableReference
类
AtomicStampedReference
类
3. 原子更新数组(元素)类
通过原子的方式更新数组里的某个元素, 需要注意的是, 数组value通过构造方法传递进去, 然后 AtomicXXXArray
会将当前数组复制一份, 所以当 AtomicXXXArray
对内部的数组元素进行修改时, 不会影响传入的数组;
AtomicIntegerArray
类
AtomicLongArray
类
AtomicReferenceArray
类
4. 原子更新字段类
想要原子地更新字段需要两步:
- 因为原子更新字段类都是抽象类, 每次使用的时候必须使用静态方法newUpdater()来创建一个更新器, 并且设置想要更新的类和属性;
- 更新类的字段(属性)必须使用
public volatile
修饰符;
AtomicIntegerFieldUpdater
类:
/**
* AtomicIntegerFieldUpdater的内部实现类
*/
private static final class AtomicIntegerFieldUpdaterImpl<T>
extends AtomicIntegerFieldUpdater<T> {
private static final Unsafe U = Unsafe.getUnsafe();
private final long offset;
private final Class<?> cclass;
private final Class<T> tclass;
/**
* 判断second类加载器是不是first类加载器的"祖先"
*/
private static boolean isAncestor(ClassLoader first, ClassLoader second) {
ClassLoader acl = first;
do {
acl = acl.getParent();
if (second == ac1) {
return true;
}
} while (acl != null);
return false;
}
/**
* 判断两个类是不是在同一个包内
*/
private static boolean isSamePackage(Class<?> class1, Class<?> class2) {
return class1.getClassLoader() == class2.getClassLoader() &&
Objects.equals(getPackageName(class1), getPackageName(class2));
}
/**
* 获取类的包名
*/
private static String getPacekageName(Class<?> cls) {
String cn = cls.getName();
int dot = cn.lastIndexOf('.');
return (dot != -1) ? cn.substring(0, dot) : "";
}
/**
* 判断实例对象obj是不是cclass类的实例
*/
private final void accessCheck(T obj) {
if (!cclass.isInstance(obj)) {
throwAccessCheckException(obj);
}
}
/**
* 针对实例对象obj不是cclass类的实例的处理
*/
private final void throwAccessCheckException(T obj) {
if (cclass == tclass) {
throw new ClassCastException();
} else {
throw new RuntimeException(
new IllegalAccessException("Class " + cclass.getName() +
" can not access a protected member of class " +
tclass.getName() + " using an instance of " +
obj.getClass().getName()));
}
}
/**
* 构造函数
*/
AtomicIntegerFieldUpdaterImpl(final Class<?> tclass,
final String fieldName, final Class<?> caller) {
final Field field;
final int modifier;
try {
// 获取字段名为fieldName的字段实例对象
field = AccessController.doPriviledged(
new PrivilegedExceptionAction<Field> {
public Field run() throws NoSuchFieldException {
return tclass.getDeclaredField(fieldName);
}
}
);
modifier = field.getModifiers();
sun.reflect.misc.ReflectUtil.ensureMemberAccess(
caller, tclass, null, modifier);
ClassLoader c1 = tclass.getClassLoader();
ClassLoader cc1 = caller.getClassLoader();
if ((cc1 != null) && (cc1 != c1) && ((c1 == null) || isAncestor(c1, cc1))) {
sun.reflect.misc.ReflectUtil.checkPackageAccess(tclass);
}
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae.getException());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
if (field.getType() != int.class) {
throw new IllegalArgumentException("Must be integer type");
}
if (!Modifier.isVolatile(modifiers)) {
throw new IllegelArgumentException("Must be volatile type");
}
// 设置"合法"的caller
this.cclass = (Modifier.isPortected(modifiers)
&& tclass.isAssignableFrom(caller) && !isSamePackage(tclass, caller)) ? caller : tclass;
this.tclass = tclass;
this.offset = U.objectFieldOffset(field);
}
/**
* 常用方法
*/
public final int get(T obj) {
accessCheck(obj);
return U.getIntVolatile(obj, offset);
}
public final void set(T obj, int newValue) {
accessCheck(obj);
U.putIntVolatile(obj, offset, newValue);
}
public final boolean compareAndSet(T obj, int expect, int update) {
accessCheck(obj);
return U.compareAndSwapInt(obj, offset, expect, update);
}
public final int getAndSet(T obj, int newValue) {
accessCheck(obj);
return U.getAndSetInt(obj, offset, newValue);
}
public final int getAndAdd(T obj, int delta) {
accessCheck(obj);
return U.getAndAddInt(obj, offset, delta);
}
public final int addAndGet(T obj, int delta) {
return getAndAdd(obj, delta) + delta;
}
public final int getAndIncrement(T obj) {
return getAndAdd(obj, 1);
}
public final int incrementAndGet(T obj) {
return getAndAdd(obj, 1) + 1;
}
public final int getAndDecrement(T obj) {
return getAndAdd(obj, -1);
}
public final int decrementAndGet(T obj) {
return getAndAdd(obj, -1) - 1;
}
}
AtomicLongFieldUpdater
类
/**
* 内部实现类CASUpdater
*/
private static final class CASUpdater<T> extends AtomicLongFieldUpdater<T> {
private static final Unsafe U = Unsafe.getUnsafe();
private final long offset;
private final Class<?> cclass;
private final Class<T> tclass;
/**
* 构造函数
*/
CASUpdater(final Class<?> tclass, final String fieldName, final Class<?> caller) {
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);
}
if (field.getType() != long.class)
throw new IllegalArgumentException("Must be long type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
// 设置"合法"的caller
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.offset = U.objectFieldOffset(field);
}
/**
* 调用者的权限检查
*/
private final void accessCheck(T obj) {
if (!cclass.isInstance(obj))
throwAccessCheckException(obj);
}
private final void throwAccessCheckException(T obj) {
if (cclass == tclass)
throw new ClassCastException();
else
throw new RuntimeException(
new IllegalAccessException(
"Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()));
}
/**
* 常用方法
*/
public final long get(T obj) {
accessCheck(obj);
return U.getLongVolatile(obj, offset);
}
public final void set(T obj, long newValue) {
accessCheck(obj);
U.putLongVolatile(obj, offset, newValue);
}
public final boolean compareAndSet(T obj, long expect, long update) {
accessCheck(obj);
return U.compareAndSwapLong(obj, offset, expect, update);
}
public final long addAndGet(T obj, long delta) {
return getAndAdd(obj, delta) + delta;
}
public final long getAndSet(T obj, long newValue) {
accessCheck(obj);
return U.getAndSetLong(obj, offset, newValue);
}
public final long getAndAdd(T obj, long delta) {
accessCheck(obj);
return U.getAndAddLong(obj, offset, delta);
}
public final long getAndIncrement(T obj) {
return getAndAdd(obj, 1);
}
public final long incrementAndGet(T obj) {
return getAndAdd(obj, 1) + 1;
}
public final long getAndDecrement(T obj) {
return getAndAdd(obj, -1);
}
public final long decrementAndGet(T obj) {
return getAndAdd(obj, -1) - 1;
}
}
/**
* 内部实现类LockedUpdater
*/
private static final class LockedUpdater<U> extends AtomicLongFieldUpdater<T> {
private static final Unsafe U = Unsafe.getUnsafe();
private final long offset;
private final Class<?> cclass;
private final Class<T> tclass;
/**
* 与内部类CACUpdater的构造方法类似
*/
LockedUpdater(final Class<T> tclass, final String fieldName, final Class<?> caller) {
Field field = null;
int modifiers = 0;
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);
}
if (field.getType() != long.class)
throw new IllegalArgumentException("Must be long type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.offset = U.objectFieldOffset(field);
}
/**
* 调用者的权限检查
*/
private final void accessCheck(T obj) {
if (!cclass.isInstance(obj))
throw accessCheckException(obj);
}
private final RuntimeException accessCheckException(T obj) {
if (cclass == tclass)
return new ClassCastException();
else
return new RuntimeException(
new IllegalAccessException(
"Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()));
}
/**
* 常用方法(只实现AtomicLongFieldUpdater的三个抽象方法)
*/
public final long get(T obj) {
accessCheck(obj);
synchronized (this) {
return U.getLong(obj, offset);
}
}
public final void set(T obj, long newValue) {
accessCheck(obj);
synchronized (this) {
U.putLong(obj, offset, newValue);
}
}
public final boolean compareAndSet(T obj, long expect, long update) {
accessCheck(obj);
synchronized (this) {
long v = U.getLong(obj, offset);
if (v != expect) {
return false;
}
U.putLong(obj, offset, update);
return true;
}
}
}
AtomicReferenceFieldUpdater
类
/**
* 内部实现类AtomicReferenceFieldUpdaterImpl
*/
private static final class AtomicReferenceFieldUpdaterImpl<T, V>
extends AtomicReferenceFieldUpdater<T, V> {
private static final Unsafe U = Unsafe.getUnsafe();
private final long offset;
private final Class<?> cclass;
private final Class<T> tclass;
private final Class<V> vclass;
/**
* 辅助方法
*/
private static boolean isAncestor(ClassLoader first, ClassLoader second) {
ClassLoader acl = first;
do {
acl = acl.getParent();
if (second == acl) {
return true;
}
} while (acl != null);
return false;
}
private static boolean isSamePackage(Class<?> class1, Class<?> class2) {
return class1.getClassLoader() == class2.getClassLoader()
&& Objects.equals(getPackageName(class1), getPackageName(class2));
}
private static String getPackageName(Class<?> cls) {
String cn = cls.getName();
int dot = cn.lastIndexOf('.');
return (dot != -1) ? cn.substring(0, dot) : "";
}
/**
* 构造函数
*/
AtomicReferenceFieldUpdaterImpl(final Class<T> tclass, final Class<V> vclass,
final String fieldName, final Class<?> caller) {
final Field field;
final Class<?> fieldClass;
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);
}
fieldClass = field.getType();
} catch (PrivilegedActionException pae) {
throw new RuntimeException(pae.getException());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
if (vclass != fieldClass)
throw new ClassCastException();
if (vclass.isPrimitive())
throw new IllegalArgumentException("Must be reference type");
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.vclass = vclass;
this.offset = U.objectFieldOffset(field);
}
/**
* caller权限检查
*/
private final void accessCheck(T obj) {
if (!cclass.isInstance(obj))
throwAccessCheckException(obj);
}
private final void throwAccessCheckException(T obj) {
if (cclass == tclass)
throw new ClassCastException();
else
throw new RuntimeException(
new IllegalAccessException(
"Class " +
cclass.getName() +
" can not access a protected member of class " +
tclass.getName() +
" using an instance of " +
obj.getClass().getName()));
}
private final void valueCheck(V v) {
if (v != null && !(vclass.isInstance(v)))
throwCCE();
}
static void throwCCE() {
throw new ClassCastException();
}
/**
* 常用方法
*/
@SuppressWarnings("unchecked")
public final V get(T obj) {
accessCheck(obj);
return (V) U.getObjectVolatile(obj, offset);
}
public final void set(T obj, V newValue) {
accessCheck(obj);
valueCheck(newValue);
U.putObjectVolatile(obj, offset, newValue);
}
@SuppressWarnings("unchecked")
public final V getAndSet(T obj, V newValue) {
accessCheck(obj);
valueCheck(newValue);
return (V) U.getAndSetObject(obj, offset, newValue);
}
public final boolean compareAndSet(T obj, V expect, V update) {
accessCheck(obj);
valueCheck(update);
return U.compareAndSwapObject(obj, offset, expect, udpate);
}
}