從JUC源碼看CAS,我做了個(gè)筆記 ......
前言
" JUC包下大量使用了CAS,工作和面試中也經(jīng)常遇到CAS,包括說(shuō)到樂(lè)觀鎖,也不可避免的想起CAS,那CAS究竟是什么? "
1.什么是CAS?
說(shuō)到CAS,基本上都會(huì)想到樂(lè)觀鎖、AtomicInteger、Unsafe ...
當(dāng)然也有可能啥也沒(méi)想到!
不管你們?cè)趺聪耄?我第一印象是樂(lè)觀鎖,畢竟做交易更新交易狀態(tài)經(jīng)常用到樂(lè)觀鎖,就自然想到這個(gè)SQL:
- update trans_order
- set order_status = 1
- where order_no = 'xxxxxxxxxxx' and order_status = 0;
其實(shí)就是 set和where里面都攜帶order_status。
那什么是CAS?
CAS就是Compare-and-Swap,即比較并替換,在并發(fā)算法時(shí)常用,并且在JUC(java.util.concurrent)包下很多類都使用了CAS。
非常常見(jiàn)的問(wèn)題就是多線程操作i++問(wèn)題。一般解決辦法就是添加 synchronized 關(guān)鍵字修飾,當(dāng)然也可以使用 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開(kāi)始了解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)方法,主要是硬件級(jí)別的原子操作。
- /**
- * @param var1 當(dāng)前對(duì)象
- * @param var2 當(dāng)前對(duì)象在內(nèi)存偏移量,Unsafe可以根據(jù)內(nèi)存偏移地址獲取數(shù)據(jù)
- * @param var4 操作值
- * @return
- */
- public final int getAndAddInt(Object var1, long var2, int var4) {
- int var5;
- do {
- // 獲取在var1在內(nèi)存的值
- var5 = this.getIntVolatile(var1, var2);
- // 將var1賦值為var5+var4, 賦值時(shí)會(huì)判斷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 的分析就忽略了。
看完代碼過(guò)程其實(shí)就是:
- 比較var1的值是否為var4,是的話將var1更新為var5。
- 如果不是的話就一直循環(huán),直到var1是var4。
3.問(wèn)題總結(jié)
- 這要是一直獲取不到,豈不是一直循環(huán)。線程多的情況下,會(huì)自旋很長(zhǎng)時(shí)間,導(dǎo)致浪費(fèi)資源。
- 你更新了, 我又給你更新回去了,你也不知道。ABA問(wèn)題!比如像這樣,A想更新值為a,還未搶到資源,這時(shí)候B進(jìn)行了更新,將對(duì)象更新為了b,然后又馬上更新回了a, 這時(shí)候A是什么都不知道的。
以樂(lè)觀鎖舉例:
- -- 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進(jìn)行版本號(hào)控制。
- -- 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 類:
- /**
- * 以原子方式設(shè)置該引用和標(biāo)志給定的更新值的值,
- * 如果當(dāng)前引用==預(yù)期的引用,并且當(dāng)前標(biāo)志==預(yù)期標(biāo)志。
- *
- * @param expectedReference 預(yù)期引用
- * @param newReference 更新的值
- * @param expectedStamp 預(yù)期標(biāo)志
- * @param newStamp 更新的標(biāo)志
- * @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)));
- }
其實(shí)就是額外增加一個(gè)標(biāo)志(stamp)來(lái)防止ABA的問(wèn)題, 類似樂(lè)觀鎖的version。
本文轉(zhuǎn)載自微信公眾號(hào)「劉志航」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系劉志航公眾號(hào)。