synchronized和AtomicInteger解決併發問題的性能比較

轉自:http://blog.csdn.net/ufo2910628/article/details/39473059

AtomicInteger,一個提供原子操作的Integer的類。在Java語言中,++i和i++操作並不是線程安全的,在使用的時候,不可避免的會用到synchronized關鍵字。而AtomicInteger則通過一種線程安全的加減操作接口,底層是有volatile修飾的變量作爲共享變量

來看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的方法來進行測試,直觀的感受下性能上的差異

 
  1. package zl.study.concurrency;  
  2. import java.util.concurrent.atomic.AtomicInteger;  
  3. public class AtomicIntegerCompareTest {  
  4.     private int value;  
  5.       
  6.     public AtomicIntegerCompareTest(int value){  
  7.         this.value = value;  
  8.     }  
  9.       
  10.     public synchronized int increase(){  
  11.         return value++;  
  12.     }  
  13.       
  14.     public static void main(String args[]){  
  15.         long start = System.currentTimeMillis();  
  16.           
  17.         AtomicIntegerCompareTest test = new AtomicIntegerCompareTest(0);  
  18.         forint i=0;i< 1000000000;i++){  
  19.             test.increase();  
  20.         }  
  21.         long end = System.currentTimeMillis();  
  22.         System.out.println("time elapse:"+(end -start));  
  23.           
  24.         long start1 = System.currentTimeMillis();  
  25.           
  26.         AtomicInteger atomic = new AtomicInteger(0);  
  27.           
  28.         forint i=0;i< 1000000000;i++){  
  29.             atomic.incrementAndGet();  
  30.         }  
  31.         long end1 = System.currentTimeMillis();  
  32.         System.out.println("time elapse:"+(end1 -start1) );  
  33.    
  34.     }  
  35. 運行結果如下:
  36. time elapse:31026
    time elapse:14101 
  37. 當然要求數據量大的時候才能發現其中的性能的差距。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章