JAVA樂觀鎖實現-CAS

來源:互聯網
上載者:User

標籤:講解   start   cin   比較   field   join   public   static   最新   

是什麼
  • 全稱compare and swap,一個CPU原子指令,在硬體層面實現的機制,體現了樂觀鎖的思想。
  • JVM用C語言封裝了彙編調用。Java的基礎庫中有很多類就是基於JNI調用C介面實現了多線程同步更新的功能。
原理

CMS有三個運算元:當前主記憶體變數的值V,執行緒區域變數預期值A,執行緒區域待更新值B。當需要更新變數值的時候,會先擷取到記憶體變數值V然後很預期值A進行比較,如果相同則更新為B,如果不同,則將最新的變數值更新到預期值中再重新嘗試上面的步驟,直到成功為止。

舉例

以基於CAS實現的AtomicInteger 類進行講解。

我們先寫一個多線程,對同一個資料類進行分別進行加減操作10000次,正確的結果應該還是0。

沒有任何多線程同步機制的代碼如下:

package priv.nanjing.testCasClass;/* * @Author : darrenqiao * *///多線程爭用的資料類class Counter {    int count = 0;    public int getCount() {        return count;    }    public void setCount(int count) {        this.count = count;    }    public void add() {        count += 1;    }    public void dec() {        count -= 1;    }}//爭用資料做加操作的線程class AddDataThread extends Thread {    Counter counter;    public AddDataThread(Counter counter) {        this.counter = counter;    }    @Override    public void run() {        for (int i = 0; i < CasClass.LOOP; ++i) {            counter.add();        }    }}//爭用資料做減法操作的線程class DecDataThread extends Thread {    Counter counter;    public DecDataThread(Counter counter) {        this.counter = counter;    }    @Override    public void run() {        for (int j = 0; j < CasClass.LOOP; j++) {            counter.dec();        }    }}public class CasClass {    final static int LOOP = 10000;    public static void main(String[] args) throws InterruptedException {        Counter counter = new Counter();        Thread addThread = new AddDataThread(counter);        Thread decThread = new DecDataThread(counter);        addThread.start();        decThread.start();        addThread.join();        decThread.join();        System.out.println(counter.getCount());    }}

 

以下是三次執行結果,每一次都不一樣。

 

為什麼會出現這個結果呢?

因為 count += 1 / count -= 1 通過javap反編譯Count.class檔案,可以看出對應的位元組碼是三條指令

      //count += 1       5: iconst_1       6: iadd       7: putfield      #12                 // Field count:I     //count 1= 1       5: iconst_1       6: isub       7: putfield      #12                 // Field count:I

所以多線程切換是,可能會造成資料更新的不同步,怎麼解決呢?

就是對被操作的資料加鎖,可以是悲觀鎖,可以是樂觀鎖,這裡使用的就是基於樂觀鎖實現的AtomicInteger類

 

package priv.nanjing.testCasClass;import java.util.concurrent.atomic.AtomicInteger;/* * @Author : darrenqiao * *///多線程爭用的資料類class Counter {    //int count = 0;    //使用AtomicInteger代替基礎資料型別 (Elementary Data Type)    AtomicInteger count = new AtomicInteger(0);    public int getCount() {        //return count;        return count.get();    }    public void add() {        //count += 1;        count.addAndGet(1);    }    public void dec() {        //count -= 1;        count.decrementAndGet();    }}//爭用資料做加操作的線程class AddDataThread extends Thread {    Counter counter;    public AddDataThread(Counter counter) {        this.counter = counter;    }    @Override    public void run() {        for (int i = 0; i < CasClass.LOOP; ++i) {            counter.add();        }    }}//爭用資料做減法操作的線程class DecDataThread extends Thread {    Counter counter;    public DecDataThread(Counter counter) {        this.counter = counter;    }    @Override    public void run() {        for (int j = 0; j < CasClass.LOOP; j++) {            counter.dec();        }    }}public class CasClass {    final static int LOOP = 10000;    public static void main(String[] args) throws InterruptedException {        Counter counter = new Counter();        Thread addThread = new AddDataThread(counter);        Thread decThread = new DecDataThread(counter);        addThread.start();        decThread.start();        addThread.join();        decThread.join();        System.out.println(counter.getCount());    }}

 

執行多次,會發現,結果只有一個:0.這樣就保證了資料更新的原子性。

 

那麼CAS有什麼缺點需要注意?

  • ABA問題:我記憶體對象從A變成B在變成A,CAS會當成沒有變化,進而去更新值,實際是有變化的。
  • 迴圈時間開銷大:一直和預期值不對的情況下,會一直迴圈。
  • 只能保證一個共用變數的原子操作。

JAVA樂觀鎖實現-CAS

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.