第六章-Java中的13个原子操作类
原子更新基本类型类
- AtomicBoolean 原子更新布尔类型
- AtomicInteger 原子更新整型
- AtomicLong 原子更新长整型
上述3类提供方法基本一致,以AtomicInteger为例
- int addAndGet(int delta)
- 以原子方式与 delta 相加
- boolean compareAndSet(int expect,int update)
- 如果输入的数值等于 expect 则以原子方式将值设置为 update
- int getAndIncrement()
- 以原子方式自增,返回值为增加之前的值
- void lazySet(int newValue)
- 使用次方法会延迟值的设置,一段时间内其他线程可能读到旧值
- int getAndSet(int newValue)
以原子方式将值设置为 newValue
源码很简单,循环调用unsafe里提供到方法
public final int getAndIncrement(){
for(;;){
int current = get();
int next = current + 1;
//注意返回的是旧值
if(compareAndSet(current,next))
return current;
}
}
public final boolean compareAndSet(int expect, int update){
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
Atomic 包里的类基本都是使用Unsafe实现的,Unsafe 一共提供了3个CAS方法
public final native boolean compareAndSwapObject(Object o,
long offset, Object expected, Object x);
public final native boolean compareAndSwapInt(Object o,
long offset, Object expected, int x);
public final native boolean compareAndSwapLong(Object o,
long offset, Object expected, long x);
在看AtomicBoolean源码,发现它是先把Boolean转化成整型,在使用compareAndSwapInt进行CAS,所以更新 char ,float ,double也可以用类似的思路。
原子更新数组
与上面同样道理
- AtomicLongArray 原子更新长整型数组
- AtomicReferenceArray 原子更新引用类型数组
- AtomicIntegerArray 原子更新整型数组
原子更新引用类型
- AtomicReference 原子更新引用类型
- AtomicReferenceFieldUpdater 原子更新引用类型里的字段
- AtomicMarkableReference 原子更新带有标记位的引用类型
原子更新字段类
- AtomicIntegerFieldUpdater 原子更新整型的字段
- AtomicLongFieldUpdater 原子更新长整型字段
- AtomicStampedReference 原子更新带有版本号的引用类型
- 可以解决使用CAS进行原子更新时可能出现的ABA问题