CAS是compareAndSet的缩写,是Unsafe类中的方法,我们来看源码:
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
CAS方法中的四个变量分别为:当前可见值,偏移量,之前预期值,需要更新的值;