Java的多線程編程模型之AtomicInteger

來源:互聯網
上載者:User

AtomicInteger,一個提供原子操作的Integer的類。在Java語言中,++i和i++操作並不是安全執行緒的,在使用的時候,不可避免的會用到synchronized關鍵字。而AtomicInteger則通過一種安全執行緒的加減操作介面。

來看AtomicInteger提供的介面。

//擷取當前的值

public final int get()

//取當前的值,並設定新的值

 public final int getAndSet(int newValue)

//擷取當前的值,並自增

 public final int getAndIncrement()

//擷取當前的值,並自減

public final int getAndDecrement()

//擷取當前的值,並加上預期的值

public final int getAndAdd(int delta)

... ...

我們在上一節提到的CAS主要是這兩個方法

    public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

    public final boolean weakCompareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

這兩個方法是名稱不同,但是做的事是一樣的,可能在後續的java版本裡面會顯示出區別來。

詳細查看會發現,這兩個介面都是調用一個unsafe的類來操作,這個是通過JNI實現的本地方法,細節就不考慮了。

 

下面是一個對比測試,我們寫一個synchronized的方法和一個AtomicInteger的方法來進行測試,直觀的感受下效能上的差異

[java]  view plain copy package zl.study.concurrency;   import java.util.concurrent.atomic.AtomicInteger;   public class AtomicIntegerCompareTest {       private int value;              public AtomicIntegerCompareTest(int value){           this.value = value;       }              public synchronized int increase(){           return value++;       }              public static void main(String args[]){           long start = System.currentTimeMillis();                      AtomicIntegerCompareTest test = new AtomicIntegerCompareTest(0);           for( int i=0;i< 1000000;i++){               test.increase();           }           long end = System.currentTimeMillis();           System.out.println("time elapse:"+(end -start));                      long start1 = System.currentTimeMillis();                      AtomicInteger atomic = new AtomicInteger(0);                      for( int i=0;i< 1000000;i++){               atomic.incrementAndGet();           }           long end1 = System.currentTimeMillis();           System.out.println("time elapse:"+(end1 -start1) );                             }   }  

結果

time elapse:31
time elapse:16
由此不難看出,通過JNI本地的CAS效能遠超synchronized關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.