CAS 的全称为“Compare And Set”,其作用是对某一个变量进行原子化的更新操作。
该算法的思想是: cas(v,e,u); v 表示要更新的变量,e 表示变量的预期值,u 表示变量的新值。当且仅当 v 的实际值等于 e 值时,才会将 v 的值设为 u,如果 v 值和 e 值不同,则说明已经有其他线程做了更新,则当前线程什么都不做,即更新失败。
注:CAS其底层是通过CPU的1条指令来完成3个步骤,因此其本身是一个原子性操作,不存在其执行某一个步骤的时候而被中断的可能。
原子类底层通过 volatile 和 CAS(Unsafe.class) 来保证了内存可见性与原子性。
AtomicBoolean boolean 原子类
AtomicInteger int 原子类
AtomicIntegerArray int 数组原子类
AtomicLong long 原子类
AtomicLongArray long 数组原子类
AtomicReference 引用对象原子类
AtomicReferenceArray 引用对象数组原子类
原子类底层方法类似,这里以 AtomicInteger 为例。
AtomicInteger 示例:
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.getAndIncrement();
System.out.println(atomicInteger.get());
AtomicReference 示例:
AtomicReference atomicReference = new AtomicReference<>();
atomicReference.set(0);
atomicReference.compareAndSet(1,2);
System.out.println(atomicReference.get());
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
/**
* 使用 Unsafe CAS 来更新操作
*/
private static final Unsafe unsafe = Unsafe.getUnsafe();
/**
* 变量 value 的内存偏移量,数据存储的内存地址
*/
private static final long valueOffset;
static {
try {
// 通过反射获取字段 value 的内存偏移量
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) {
throw new Error(ex);
}
}
/**
* 变量 value
*/
private volatile int value;
/**
* 构造方法,指定 value
*/
public AtomicInteger(int initialValue) {
value = initialValue;
}
/**
* 构造方法,value 初始为 0
*/
public AtomicInteger() {
}
/**
* 返回 value
*/
public final int get() {
return value;
}
/**
* 设置 value
*/
public final void set(int newValue) {
value = newValue;
}
/**
* 懒加载设置 value,使用该方法后,其他线程在一段时间内还会获取到旧值
*/
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
/**
* 设置新值并返回旧值
*/
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
/**
* 如果当前值为 expect,则设置为 update
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* 同 compareAndSet() ,底层调用方法相同,现在一样可能是暂时的,将来可能会不一样
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
/**
* 当前值 +1,并返回旧值
*/
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
/**
* 当前值 -1,并返回旧值
*/
public final int getAndDecrement() {
return unsafe.getAndAddInt(this, valueOffset, -1);
}
/**
* 当前值 +delta,并返回旧值
*/
public final int getAndAdd(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}
/**
* 当前值 +1,并返回新值
*/
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
/**
* 当前值 -1,并返回新值
*/
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
/**
* 当前值 +delta,并返回新值
*/
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}
/**
* 使用 IntBinaryOperator 对当前值进行计算,并更新当前值,返回旧值
*/
public final int getAndUpdate(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return prev;
}
/**
* 同 getAndUpdate()
*/
public final int updateAndGet(IntUnaryOperator updateFunction) {
int prev, next;
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
return next;
}
/**
* 使用 IntBinaryOperator 对当前值和x进行计算,并更新当前值,返回旧值
*/
public final int getAndAccumulate(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return prev;
}
/**
* 同 getAndAccumulate()
*/
public final int accumulateAndGet(int x,
IntBinaryOperator accumulatorFunction) {
int prev, next;
do {
prev = get();
next = accumulatorFunction.applyAsInt(prev, x);
} while (!compareAndSet(prev, next));
return next;
}
/**
* value 转换 String
*/
public String toString() {
return Integer.toString(get());
}
/**
* 同 get()
*/
public int intValue() {
return get();
}
/**
* 同 get()
*/
public long longValue() {
return (long) get();
}
/**
* 同 get()
*/
public float floatValue() {
return (float) get();
}
/**
* 同 get()
*/
public double doubleValue() {
return (double) get();
}
}