並發性能優化 – 降低鎖粒度
在高負載多線程應用中性能是非常重要的。為了達到更好的性能,開發者必須意識到並發的重要性。當我們需要使用並發時, 常常有一個資源必須被兩個或多個線程共享。
在這種情況下,就存在一個競爭條件,也就是其中一個線程可以得到鎖(鎖與特定資源綁定),其他想要得到鎖的線程會被阻塞。這個同步機製的實現是有代價的,為了向你提供一個好用的同步模型,JVM和操作係統都要消耗資源。有三個最重要的因素使並發的實現會消耗大量資源,它們是:
- 上下文切換
- 內存同步
- 阻塞
為了寫出針對同步的優化代碼,你必須認識到這三個因素以及如何減少它們。在寫這樣的代碼時你需要注意很多東西。在本文中,我會向你介紹一種通過降低鎖粒度的技術來減少這些因素。
讓我們從一個基本原則開始:不要長時間持有不必要的鎖。
在獲得鎖之前做完所有需要做的事,隻把鎖用在需要同步的資源上,用完之後立即釋放它。我們來看一個簡單的例子:
public class HelloSync { private Map dictionary = new HashMap(); public synchronized void borringDeveloper(String key, String value) { long startTime = (new java.util.Date()).getTime(); value = value + "_"+startTime; dictionary.put(key, value); System.out.println("I did this in "+ ((new java.util.Date()).getTime() - startTime)+" miliseconds"); } }
在這個例子中,我們違反了基本原則,因為我們創建了兩個Date對象,調用了System.out.println(),還做了很多次String連接操作,但唯一需要做同步的操作是“dictionary.put(key, value);”。讓我們來修改代碼,把同步方法變成隻包含這句的同步塊,得到下麵更優化的代碼:
public class HelloSync { private Map dictionary = new HashMap(); public void borringDeveloper(String key, String value) { long startTime = (new java.util.Date()).getTime(); value = value + "_"+startTime; synchronized (dictionary) { dictionary.put(key, value); } System.out.println("I did this in "+ ((new java.util.Date()).getTime() - startTime)+" miliseconds"); } }
上麵的代碼可以進一步優化,但這裏隻想傳達出這種想法。如果你對如何進一步優化感興趣,請參考java.util.concurrent.ConcurrentHashMap.
那麼,我們怎麼降低鎖粒度呢?簡單來說,就是通過盡可能少的請求鎖。基本的想法是,分別用不同的鎖來保護同一個類中多個獨立的狀態變量,而不是對整個類域隻使用一個鎖。我們來看下麵這個我在很多應用中見到過的簡單例子:
public class Grocery { private final ArrayList fruits = new ArrayList(); private final ArrayList vegetables = new ArrayList(); public synchronized void addFruit(int index, String fruit) { fruits.add(index, fruit); } public synchronized void removeFruit(int index) { fruits.remove(index); } public synchronized void addVegetable(int index, String vegetable) { vegetables.add(index, vegetable); } public synchronized void removeVegetable(int index) { vegetables.remove(index); } }
雜貨店主可以對他的雜貨鋪中的蔬菜和水果進行添加/刪除操作。上麵對雜貨鋪的實現,通過基本的Grocery 鎖來保護fruits和vegetables,因為同步是在方法域完成的。事實上,我們可以不使用這個大範圍的鎖,而是針對每個資源(fruits和vegetables)分別使用一個鎖。來看一下改進後的代碼:
public class Grocery { private final ArrayList fruits = new ArrayList(); private final ArrayList vegetables = new ArrayList(); public void addFruit(int index, String fruit) { synchronized(fruits) fruits.add(index, fruit); } public void removeFruit(int index) { synchronized(fruits) {fruits.remove(index);} } public void addVegetable(int index, String vegetable) { synchronized(vegetables) vegetables.add(index, vegetable); } public void removeVegetable(int index) { synchronized(vegetables) vegetables.remove(index); } }
在使用了兩個鎖後(把鎖分離),我們會發現比起之前用一個整體鎖,鎖阻塞的情況更少了。當我們把這個技術用在有中度鎖爭搶的鎖上時,優化提升會更明顯。如果把該方法應用到輕微鎖爭搶的鎖上,改進雖然比較小,但還是有效果的。但是如果把它用在有重度鎖爭搶的鎖上時,你必須認識到結果並非總是更好。
請有選擇性的使用這個技術。如果你懷疑一個鎖是重度爭搶鎖請按下麵的方法來確認是否使用上麵的技術:
- 確認你的產品會有多少爭搶度,將這個爭搶度乘以三倍或五倍(甚至10倍,如果你想準備的萬無一失)
- 基於這個爭搶度做適當的測試
- 比較兩種方案的測試結果,然後挑選出最合適的
用於改進同步性能的技術還有很多,但對所有的技術來說最基本的原則隻有一個:不要長時間持有不必要的鎖。
這條基本原則可以如我之前向你們解釋的那樣理解成“盡可能少的請求鎖”,也可以有其他解釋(實現方法),我將在之後的文章中進一步介紹。
兩個最重要的建議:
- 請了解一下 java.util.concurrent包裏的類(及其子包),因為其中有很多聰明而且有用的實現
- 並發代碼大多數都可以通過使用好的設計模式來簡化。請將 Enterprise Integration Patterns熟記於心,它們可以讓你不必熬夜。
Reference: Reduce lock granularity – Concurrency optimization from our JCG partner Adrianos Dadis at Java, Integration and the virtues of source.
- Java Concurrency Tutorial – Semaphores
- Java Concurrency Tutorial – Reentrant Locks
- Java Concurrency Tutorial – Thread Pools
- Java Concurrency Tutorial – Callable, Future
- Java Concurrency Tutorial – Blocking Queues
- Java Concurrency Tutorial – CountDownLatch
- Java Fork/Join for Parallel Programming
- Java Memory Model – Quick overview and things to notice
- Java Tutorials and Android Tutorials list
- 轉載自 並發編程網 - ifeve.com
最後更新:2017-05-23 11:02:56