AtomicIntegerArray提供的功能:整型数组的元素支持原子性更新操作
获取、设置、减一、添加(n)、增一,延迟设置
类定义
public class AtomicIntegerArray implements java.io.Serializable {
private static final long serialVersionUID = 2862133569453604235L;
private static final Unsafe unsafe = Unsafe.getUnsafe();
//第一个元素相当于对象内存开始地址(有对象头等内存字段)的偏移量
private static final int base = unsafe.arrayBaseOffset(int[].class);
private static final int shift;
//存储整型元素的数组
private final int[] array;
static {
//scale为每个元素的字节偏移量, int为4字节
int scale = unsafe.arrayIndexScale(int[].class);
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
//scale为4时,leadingzero为29,所以shift为2
//元素i位置为base+i*scale 与 base+ i << 2 等价, 乘以4相当于左移两位
shift = 31 - Integer.numberOfLeadingZeros(scale);
}
private long checkedByteOffset(int i) {
if (i < 0 || i >= array.length)
throw new IndexOutOfBoundsException("index " + i);
return byteOffset(i);
}
//计算位置i的元素的内存偏移值, base + i << shift(此处为2)
private static long byteOffset(int i) {
return ((long) i << shift) + base;
}
//getAndSet还是利用unsafe的getAndSetInt方法,
//但是要调用checkedByteOffset方法算出元素i的内存偏移值
public final int getAndSet(int i, int newValue) {
return unsafe.getAndSetInt(array, checkedByteOffset(i), newValue);
}