從JUC源碼看CAS,我做了個筆記 ......
前言
" JUC包下大量使用了CAS,工作和面試中也經常遇到CAS,包括說到樂觀鎖,也不可避免的想起CAS,那CAS究竟是什么? "
1.什么是CAS?
說到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。
2.源碼分析
- 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 的分析就忽略了。
看完代碼過程其實就是:
- 比較var1的值是否為var4,是的話將var1更新為var5。
- 如果不是的話就一直循環,直到var1是var4。
3.問題總結
- 這要是一直獲取不到,豈不是一直循環。線程多的情況下,會自旋很長時間,導致浪費資源。
- 你更新了, 我又給你更新回去了,你也不知道。ABA問題!比如像這樣,A想更新值為a,還未搶到資源,這時候B進行了更新,將對象更新為了b,然后又馬上更新回了a, 這時候A是什么都不知道的。
以樂觀鎖舉例:
- -- 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。
本文轉載自微信公眾號「劉志航」,可以通過以下二維碼關注。轉載本文請聯系劉志航公眾號。