hello,各位,本次一起学习下原子操作类的最后一类,原子操作字段类
具体有如下四个:
AtomicIntegerFieldUpdater: 原子操作整型的字段类。AtomicLongFieldUpdater: 原子操作长整型字段类。 AtomicStampedFieldUpdater: 原子操作带版本号的引用类。 AtomicReferenceFieldUpdater:原子操作的字段引用类。
我们照例使用AtomicIntegerFieldUpdater类作为例子,其他的实现简略讲解。
首先需要了解下AtomicIntegerFieldUpdater类的使用场景:
它是用在一个类实例的int属性需要原子操作的场景,就是说,这个实例仅该属性需要原子操作。
还需要满足以下条件:
1.这个int属性必须是volatile属性的,如果不是,那谁也无法保证可见性,也就无法保证原子性。
2.属性必须是实例属性,不能是static属性,因为需要得到实例后反射执行。
3.不能是常量,即不能是final属性,常量无法修改。
AtomicIntegerFieldUpdater类的源码
如下所示://虚拟类
public abstract class AtomicIntegerFieldUpdater {
@CallerSensitive
public static AtomicIntegerFieldUpdater newUpdater(Class tclass,
String fieldName) {
return new AtomicIntegerFieldUpdaterImpl
(tclass, fieldName, Reflection.getCallerClass());
}
public abstract boolean compareAndSet(T obj, int expect, int update);
public abstract boolean weakCompareAndSet(T obj, int expect, int update);
public abstract void set(T obj, int newValue);
public abstract void lazySet(T obj, int newValue);
public abstract int get(T obj);
public int getAndSet(T obj, int newValue) {
int prev;
do {
prev = get(obj);
} while (!compareAndSet(obj, prev, newValue));
return prev;
}
public int getAndIncrement(T obj) {
int prev, next;
do {
prev = get(obj);
next = prev + 1;
} while (!compareAndSet(obj, prev, next));
return prev;
}
public int getAndDecrement(T obj) {
int prev, next;
do {
prev = get(obj);
next = prev - 1;
} while (!compareAndSet(obj, prev, next));
return prev;
}
public int getAndAdd(T obj, int delta) {
int prev, next;
do {
prev = get(obj);
next = prev + delta;
} while (!compareAndSet(obj, prev, next));
return prev;
}
public int incrementAndGet(T obj) {
int prev, next;
do {
prev = get(obj);
next = prev + 1;
} while (!compareAndSet(obj, prev, next));
return next;
}
public int decrementAndGet(T obj) {
int prev, next;
do {
prev = get(obj);
next = prev - 1;
} while (!compareAndSet(obj, prev, next));
return next;
}
public int addAndGet(T obj, int delta) {
int prev, next;
do {
prev = get(obj);
next = prev + delta;
} while (!compareAndSet(obj, prev, next));
return next;
}
public final int getAndUpdate(T obj, IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get(obj);
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(obj, prev, next));
return prev;
}
public final int updateAndGet(T obj, IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get(obj);
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(obj, prev, next));
return next;
}
//IntBinaryOperator函数式接口 的运算
public final int getAndAccumulate(T obj, int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get(obj);
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(obj, prev, next));
return prev;
}
public final int accumulateAndGet(T obj, int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get(obj);
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(obj, prev, next));
return next;
}
private final Class> cclass;
/** class holding the field */
private final Class tclass;
//构造器
AtomicIntegerFieldUpdaterImpl(final Class tclass,
final String fieldName,
final Class> caller) {
final Field field;
final int modifiers;
try {
//获取属性,并标记该属性的特权访问
field = AccessController.doPrivileged(
new PrivilegedExceptionAction() {
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();
//如果非同个类加载器,或者caller不在被调用类的调用链中,检查包的权限
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);
}
//检查类型,必须是int型,Integer都不行
if (field.getType() != int.class)
throw new IllegalArgumentException("Must be integer type");
//必须是volatile型
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
this.tclass = tclass;
//计算该属性的偏移量(地址)
this.offset = U.objectFieldOffset(field);
}
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 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 boolean compareAndSet(T obj, int expect, int update) {
accessCheck(obj);
return U.compareAndSwapInt(obj, offset, expect, update);
}
public final boolean weakCompareAndSet(T obj, int expect, int update) {
accessCheck(obj);
return U.compareAndSwapInt(obj, offset, expect, update);
}
public final void set(T obj, int newValue) {
accessCheck(obj);
U.putIntVolatile(obj, offset, newValue);
}
public final void lazySet(T obj, int newValue) {
accessCheck(obj);
U.putOrderedInt(obj, offset, newValue);
}
public final int get(T obj) {
accessCheck(obj);
return U.getIntVolatile(obj, offset);
}
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 getAndIncrement(T obj) {
return getAndAdd(obj, 1);
}
public final int getAndDecrement(T obj) {
return getAndAdd(obj, -1);
}
public final int incrementAndGet(T obj) {
return getAndAdd(obj, 1) + 1;
}
public final int decrementAndGet(T obj) {
return getAndAdd(obj, -1) - 1;
}
public final int addAndGet(T obj, int delta) {
return getAndAdd(obj, delta) + delta;
}
}
}
总结
如上的代码,可以看到,该类的构造器通过反射方法得到这个field的信息,检查访问权限,并得到该属性在对象类中的偏移量。
获得偏移量之后,再使用之前介绍过的unsafe的compareAndSwapInt来进行CAS操作。
其他几个类实现方法类似,这里不再赘述。
附图:
喜欢的小伙伴关注下本人公众号:暖爸的java家园