前言
JUC包下大量使用了CAS,工作和面试中也经常遇到CAS,包括说到乐观锁,也不可避免的想起CAS,那CAS究竟是什么?
公众号:liuzhihangs,记录工作学习中的技术、开发及源码笔记;时不时分享一些生活中的见闻感悟。欢迎大佬来指导!
说到CAS,基本上都会想到乐观锁、AtomicInteger、Unsafe …
当然也有可能啥也没想到!
不管你们怎么想, 我第一印象是乐观锁,毕竟做交易更新交易状态经常用到乐观锁,就自然想到这个SQL:
update trans_order
set order_status = 1
where order_no = 'xxxxxxxxxxx' and order_status = 0;
其实就是 set和where里面都携带order_status。
那什么是CAS?
CAS就是Compare-and-Swap
,即比较并替换,在并发算法时常用,并且在JUC(java.util.concurrent)包下很多类都使用了CAS。
非常常见的问题就是多线程操作i++问题。一般解决办法就是添加 synchronized 关键字修饰,当然也可以使用 AtomicInteger 代码举例如下:
public class CasTest {
private static final CountDownLatch LATCH = new CountDownLatch(10);
private static int NUM_I = 0;
private static volatile int NUM_J = 0;
private static final AtomicInteger NUM_K = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
threadPool.execute(new Runnable() {
public void run() {
for (int j = 0; j < 10000; j++) {
NUM_I++;
NUM_J++;
NUM_K.incrementAndGet();
}
LATCH.countDown();
}
});
}
LATCH.await();
System.out.println("NUM_I = " + NUM_I);
System.out.println("NUM_J = " + NUM_J);
System.out.println("NUM_K = " + NUM_K.get());
threadPool.shutdown();
}
}
下面就从AtomicInteger
开始了解CAS。
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
public final int decrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, -1) - 1;
}
}
可以看出里面使用了Unsafe
类下的getAndAddInt
方法,Unsafe
类很多方法是本地(native)方法,主要是硬件级别的原子操作
。
/**
* @param var1 当前对象
* @param var2 当前对象在内存偏移量,Unsafe可以根据内存偏移地址获取数据
* @param var4 操作值
* @return
*/
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
// 获取在var1在内存的值
var5 = this.getIntVolatile(var1, var2);
// 将var1赋值为var5+var4, 赋值时会判断var1是否为var5
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
// 原子操作
public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);
至于 compareAndSwapInt 的分析就忽略了。
看完代码过程其实就是:
以乐观锁举例:
-- 0 -> 1
update trans_order
set order_status = 1
where order_no = 'xxxxxxxxxxx' and order_status = 0;
-- 1 -> 0
update trans_order
set order_status = 1
where order_no = 'xxxxxxxxxxx' and order_status = 0;
-- 0 -> 1
update trans_order
set order_status = 1
where order_no = 'xxxxxxxxxxx' and order_status = 0;
解决办法可以添加version进行版本号控制。
-- 0 -> 1
update trans_order
set order_status = 1
where order_no = 'xxxxxxxxxxx' and order_status = 0 and version = 0;
-- 1 -> 0
update trans_order
set order_status = 1
where order_no = 'xxxxxxxxxxx' and order_status = 0 and version = 1;
-- 0 -> 1
update trans_order
set order_status = 1
where order_no = 'xxxxxxxxxxx' and order_status = 0 and version = 0;
代码中可以看 AtomicStampedReference
类:
/**
* 以原子方式设置该引用和标志给定的更新值的值,
* 如果当前引用==预期的引用,并且当前标志==预期标志。
*
* @param expectedReference 预期引用
* @param newReference 更新的值
* @param expectedStamp 预期标志
* @param newStamp 更新的标志
* @return {@code true} if successful
*/
public boolean compareAndSet(V expectedReference,
V newReference,
int expectedStamp,
int newStamp) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
expectedStamp == current.stamp &&
((newReference == current.reference &&
newStamp == current.stamp) ||
casPair(current, Pair.of(newReference, newStamp)));
}
其实就是额外增加一个标志(stamp
)来防止ABA的问题, 类似乐观锁的version。