CAS算法
CAS的全称为Compare-And-Swap,它是一条CPU并发原语。它的功能是判断内存某个位置的值是否为预期值,如果是则更改为新的值,这个过程是原子性的。AtomicInteger类主要利用CAS(compare and swap) + volatile和native方法来保证原子操作,从而避免 synchronized的高开销,执行效率大为提升。
代码示例:
public static AtomicInteger quantity = new AtomicInteger();//原子类
public void compareAndSet() {
int oldV ;
int newV;
do {
oldV = quantity.get(); |非原子性
newV = oldV - 1;// 这里需要判断新值是否小于0,如果小于0则抛出异常 | 非原子性
quantity.set(newV);
} while (!quantity.compareAndSet(oldV, newV));
}
缺点:
如果使用循环写法,在高并发场景下时间长开销很大