Java併發編程總結2——慎用CAS

 

1、CAS和synchronized適用場景java

一、對於資源競爭較少的狀況,使用synchronized同步鎖進行線程阻塞和喚醒切換以及用戶態內核態間的切換操做額外浪費消耗cpu資源;而CAS基於硬件實現,不須要進入內核,不須要切換線程,操做自旋概率較少,所以能夠得到更高的性能。dom

二、對於資源競爭嚴重的狀況,CAS自旋的機率會比較大,從而浪費更多的CPU資源,效率低於synchronized。以java.util.concurrent.atomic包中AtomicInteger類爲例,其getAndIncrement()方法實現以下:post

複製代碼
public final int getAndIncrement() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return current;
        }
}
複製代碼

若是compareAndSet(current, next)方法成功執行,則直接返回;若是線程競爭激烈,致使compareAndSet(current, next)方法一直不能成功執行,則會一直循環等待,直到耗盡cpu分配給該線程的時間片,從而大幅下降效率。性能

 

2、CAS錯誤的使用場景測試

複製代碼
1 public class CASDemo {
 2     private final int THREAD_NUM = 1000;
 3     private final int MAX_VALUE = 20000000;
 4     private AtomicInteger casI = new AtomicInteger(0);
 5     private int syncI = 0;
 6     private String path = "/Users/pingping/DataCenter/Books/Linux/Linux經常使用命令詳解.txt";
 7 
 8     public void casAdd() throws InterruptedException {
 9         long begin = System.currentTimeMillis();
10         Thread[] threads = new Thread[THREAD_NUM];
11         for (int i = 0; i < THREAD_NUM; i++) {
12             threads[i] = new Thread(new Runnable() {
13                 public void run() {
14                     while (casI.get() < MAX_VALUE) {
15                         casI.getAndIncrement();
16                     }
17                 }
18             });
19             threads[i].start();
20         }
21         for (int j = 0; j < THREAD_NUM; j++) {
22             threads[j].join();
23         }
24         System.out.println("CAS costs time: " + (System.currentTimeMillis() - begin));
25     }
26 
27     public void syncAdd() throws InterruptedException {
28         long begin = System.currentTimeMillis();
29         Thread[] threads = new Thread[THREAD_NUM];
30         for (int i = 0; i < THREAD_NUM; i++) {
31             threads[i] = new Thread(new Runnable() {
32                 public void run() {
33                     while (syncI < MAX_VALUE) {
34                         synchronized ("syncI") {
35                             ++syncI;
36                         }
37                     }
38                 }
39             });
40             threads[i].start();
41         }
42         for (int j = 0; j < THREAD_NUM; j++)
43             threads[j].join();
44         System.out.println("sync costs time: " + (System.currentTimeMillis() - begin));
45     }
46 }
複製代碼

在個人雙核cpu上運行,結果以下:優化

可見在不一樣的線程下,採用CAS計算消耗的時間遠多於使用synchronized方式。緣由在於第15行atom

14                     while (casI.get() < MAX_VALUE) {
15                         casI.getAndIncrement();
16                     }

的操做是一個耗時很是少的操做,15行執行完以後會馬上進入循環,繼續執行,從而致使線程衝突嚴重。spa

 

3、改進的CAS使用場景.net

爲了解決上述問題,只須要讓每一次循環執行的時間變長,便可以大幅減小線程衝突。修改代碼以下:線程

複製代碼
1 public class CASDemo {
 2     private final int THREAD_NUM = 1000;
 3     private final int MAX_VALUE = 1000;
 4     private AtomicInteger casI = new AtomicInteger(0);
 5     private int syncI = 0;
 6     private String path = "/Users/pingping/DataCenter/Books/Linux/Linux經常使用命令詳解.txt";
 7 
 8     public void casAdd2() throws InterruptedException {
 9         long begin = System.currentTimeMillis();
10         Thread[] threads = new Thread[THREAD_NUM];
11         for (int i = 0; i < THREAD_NUM; i++) {
12             threads[i] = new Thread(new Runnable() {
13                 public void run() {
14                     while (casI.get() < MAX_VALUE) {
15                         casI.getAndIncrement();
16                         try (InputStream in = new FileInputStream(new File(path))) {
17                                 while (in.read() != -1);
18                         } catch (IOException e) {
19                             e.printStackTrace();
20                         }
21                     }
22                 }
23             });
24             threads[i].start();
25         }
26         for (int j = 0; j < THREAD_NUM; j++)
27             threads[j].join();
28         System.out.println("CAS Random costs time: " + (System.currentTimeMillis() - begin));
29     }
30 
31     public void syncAdd2() throws InterruptedException {
32         long begin = System.currentTimeMillis();
33         Thread[] threads = new Thread[THREAD_NUM];
34         for (int i = 0; i < THREAD_NUM; i++) {
35             threads[i] = new Thread(new Runnable() {
36                 public void run() {
37                     while (syncI < MAX_VALUE) {
38                         synchronized ("syncI") {
39                             ++syncI;
40                         }
41                         try (InputStream in = new FileInputStream(new File(path))) {
42                             while (in.read() != -1);
43                         } catch (IOException e) {
44                             e.printStackTrace();
45                         }
46                     }
47                 }
48             });
49             threads[i].start();
50         }
51         for (int j = 0; j < THREAD_NUM; j++)
52             threads[j].join();
53         System.out.println("sync costs time: " + (System.currentTimeMillis() - begin));
54     }
55 }
複製代碼

在while循環中,增長了一個讀取文件內容的操做,該操做大概須要耗時40ms,從而能夠減小線程衝突。測試結果以下:

可見在資源衝突比較小的狀況下,採用CAS方式和synchronized同步效率差很少。爲何CAS相比synchronized沒有得到更高的性能呢?

 

測試使用的jdk爲1.7,而從jdk1.6開始,對鎖的實現引入了大量的優化,如鎖粗化(Lock Coarsening)、鎖消除(Lock Elimination)、輕量級鎖(Lightweight Locking)、偏向鎖(Biased Locking)、適應性自旋(Adaptive Spinning)等技術來減小鎖操做的開銷。而其中自旋鎖的原理,相似於CAS自旋,甚至比CAS自旋更爲優化。具體內容請參考 深刻JVM鎖機制1-synchronized。

傳送門:http://blog.csdn.net/chen77716/article/details/6618779

 

4、總結

一、使用CAS在線程衝突嚴重時,會大幅下降程序性能;CAS只適合於線程衝突較少的狀況使用。

二、synchronized在jdk1.6以後,已經改進優化。synchronized的底層實現主要依靠Lock-Free的隊列,基本思路是自旋後阻塞,競爭切換後繼續競爭鎖,稍微犧牲了公平性,但得到了高吞吐量。在線程衝突較少的狀況下,能夠得到和CAS相似的性能;而線程衝突嚴重的狀況下,性能遠高於CAS。

相關文章
相關標籤/搜索