背景知識:
- sun.misc.Unsafe 類的運用,參見 http://ifeve.com/sun-misc-unsafe/
介紹:
AtomicXXXArray 包括AtomicIntegerArray,AtomicLongArray,AtomicReferenceArray 三個主要類別琼了,是對不同類型數(shù)組進行一個原子操作實現(xiàn)顽腾。實現(xiàn)方式為CAS
實現(xiàn)原理:
類在初始化時獲取數(shù)組在起始位置以及偏移量
static {
//獲取數(shù)組的元素所占空間大小欣除,即比例因子
int scale = unsafe.arrayIndexScale(int[].class);
//判斷其必須為2的指數(shù)倍
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
//獲取該比例因子二進制中1 在第幾位岔激,(十進制)4 = (二進制)100茄蚯,故計算出來的shift 為 3
shift = 31 - Integer.numberOfLeadingZeros(scale);
}
通過shift及base 查找下標(biāo)為 i 的偏移量
private long checkedByteOffset(int i) {
if (i < 0 || i >= array.length)
throw new IndexOutOfBoundsException("index " + i);
return byteOffset(i);
}
//可以證明 i * scale + base == i << shift + base
private static long byteOffset(int i) {
return ((long) i << shift) + base;
}
獲取到偏移量,便可以通過
unsafe.getIntVolatile(array, offset);
來獲取到下標(biāo) i 的值了。
根據(jù)數(shù)組和偏移量辙浑,便可根據(jù)CAS方式進行數(shù)據(jù)的更新了,CAS實現(xiàn)類似于AtomicBoolean