AtomicInteger 类
其余几个类与此实现类似
增
/*** Atomically increments by one the current value.** @return the previous value*/public final int getAndIncrement() {return unsafe.getAndAddInt(this, valueOffset, 1);}
减
/*** Atomically decrements by one the current value.** @return the previous value*/public final int getAndDecrement() {return unsafe.getAndAddInt(this, valueOffset, -1);}
valueOffset 值,在 AtomicInteger 类的静态代码块中初始化,unsafe.objectFieldOffset 用户获取某个字段相对Java对象的“起始地址”的偏移量
static {try {valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));} catch (Exception ex) { throw new Error(ex); }}
UnSafe类
此处三个参数,分别表示
/*** Atomically adds the given value to the current value of a field* or array element within the given object <code>o</code>* at the given <code>offset</code>.** @param o object/array to update the field/element in 对象* @param offset field/element offset 对象属性偏移值* @param delta the value to add 变化值* @return the previous value* @since 1.8*/public final int getAndAddInt(Object o, long offset, int delta) {int v;do {v = getIntVolatile(o, offset);} while (!compareAndSwapInt(o, offset, v, v + delta));return v;}
ABA 问题
AtomicXXXFieldUpdater
为什么需要?如果一个类是自己编写的,可以直接定义成员变量为 Atomic类,但如果是一个已有的类,在不能修改源代码的情况下,要想实现对其成员变量的院子操作,就需要AtomicXXXFieldUpdater类了
- AtomicIntegerFieldUpdater
- AtomicLongFieldUpdater
- AtomicReferenceFieldUpdater
实现原理
构造对象时,传入要修改的类和对应的成员变量的名字,内部会通过反射拿到这个类的成员变量的偏移值,在真实需要修改某个对象的成员变量值的时候,再传入相应的对象,最后调用UnSafe类的方法(类似getAndAddInt方法,参数有 object,offset值,变化值)
Atomic 数组操作类
- AtomicIntegerArray
- AtomicLongArray
- AtomicReferenceArray
这里不是说整个数组的操作是原子的,而是针对数组的一个元素的原子操作,所以相关操作方法都多个一个参数,数组下标 i
实现原理
把数组下标 i 转换为相应的内存偏移量,然后底层函数还是 UnSafe 的 compareAndSwapInt 等
