如何提高 Java 中鎖的效能

來源:互聯網
上載者:User

如何提高 Java 中鎖的效能

兩個月前向Plumbr公司引進線程死結的檢測之後,我們開始收到一些類似於這樣的詢問:“棒極了!現在我知道造成程式出現效能問題的原因了,但是接下來該怎麼做呢?”

我們努力為自己的產品所遇到的問題思考解決辦法,但在這篇文章中我將給大家分享幾種常用的技術,包括分離鎖、並行資料結構、保護資料而非代碼、縮小鎖的作用範圍,這幾種技術可以使我們不使用任何工具來檢測死結。

鎖不是問題的根源,鎖之間的競爭才是

通常在多線程的代碼中遇到效能方面的問題時,一般都會抱怨是鎖的問題。畢竟鎖會降低程式的運行速度和其較低的擴充性是眾所周知的。因此,如果帶著這種“常識”開始最佳化代碼,其結果很有可能是在之後會出現討人厭的並發問題。

因此,明白競爭鎖和非競爭鎖的不同是非常重要的。當一個線程試圖進入 另一個線程正在執行的同步塊或方法時會觸發鎖競爭。該線程會被強制進入等待狀態,直到第一個線程執行完同步塊並且已經釋放了監視器。當同一時間只有一個線 程嘗試執行同步的代碼地區時,鎖會保持非競爭的狀態。

事實上,在非競爭的情況下和大多數的應用中,JVM已經對同步進行了最佳化。非競爭鎖在執行過程中不會帶來任何額外的開銷。因此,你不應該因為效能問題抱怨鎖,應該抱怨的是鎖的競爭。當有了這個認識之後,讓我們來看下能做些什麼,以降低競爭的可能性或減少競爭的期間。

保護資料而非代碼

解決安全執行緒問題的一個快速的方法就是對整個方法的可訪問性加鎖。例如下面這個例子,試圖通過這種方法來建立一個線上撲克遊戲伺服器:

 
  1. class GameServer { 
  2.   public Map<<String, List<Player>> tables = new HashMap<String, List<Player>>(); 
  3.  
  4.   public synchronized void join(Player player, Table table) { 
  5.     if (player.getAccountBalance() > table.getLimit()) { 
  6.       List<Player> tablePlayers = tables.get(table.getId()); 
  7.       if (tablePlayers.size() < 9) { 
  8.         tablePlayers.add(player); 
  9.       } 
  10.     } 
  11.   } 
  12.   public synchronized void leave(Player player, Table table) {/*body skipped for brevity*/} 
  13.   public synchronized void createTable() {/*body skipped for brevity*/} 
  14.   public synchronized void destroyTable(Table table) {/*body skipped for brevity*/} 

作者的意圖是好的——當一個新的玩家加入牌桌 時,必須確保牌桌上的玩家個數不會超過牌桌可以容納的玩家總個數9。

但是這種解決辦法事實上無論何時都要對玩家進入牌桌進行控制——即使是在伺服器的訪問量較小的時候也是這樣,那些等 待鎖釋放的線程註定會頻繁的觸發系統的競爭事件。包含對賬戶餘額和牌桌限制檢查的鎖定塊很可能大幅提高叫用作業的開銷,而這無疑會增加競爭的可能性和持續 時間。

解決的第一步就是確保我們保護的是資料,而不是從方法聲明移到方法體中的那段同步聲明。對於上面那個簡單的例子來說,可能改變不大。但是我們要站在整個遊戲服務的介面之上來考慮,而不是單單的一個join()方法。

 
  1. class GameServer { 
  2.   public Map<String, List<Player>> tables = new HashMap<String, List<Player>>(); 
  3.  
  4.   public void join(Player player, Table table) { 
  5.     synchronized (tables) { 
  6.       if (player.getAccountBalance() > table.getLimit()) { 
  7.         List<Player> tablePlayers = tables.get(table.getId()); 
  8.         if (tablePlayers.size() < 9) { 
  9.           tablePlayers.add(player); 
  10.         } 
  11.       } 
  12.     } 
  13.   } 
  14.   public void leave(Player player, Table table) {/* body skipped for brevity */} 
  15.   public void createTable() {/* body skipped for brevity */} 
  16.   public void destroyTable(Table table) {/* body skipped for brevity */} 

原本可能只是一個小小的改變,影響的可是整個類的行為方式。玩家無論何時加入牌桌,先前的同步方法都會對整個GameServer執行個體加鎖,進而會與那些同時試圖離開牌桌的玩家產生競爭。將鎖從方法聲明移到方法體中會延遲鎖的載入,進而降低了鎖競爭的可能性。

縮小鎖的作用範圍

現在,當確信了需要保護的是資料而非程式後,我們應該確保我們只在必要的地方加鎖——例如當上面的代碼被重構之後:

 
  1. public class GameServer { 
  2.   public Map<String, List<Player>> tables = new HashMap<String, List<Player>>(); 
  3.  
  4.   public void join(Player player, Table table) { 
  5.     if (player.getAccountBalance() > table.getLimit()) { 
  6.       synchronized (tables) { 
  7.         List<Player> tablePlayers = tables.get(table.getId()); 
  8.         if (tablePlayers.size() < 9) { 
  9.           tablePlayers.add(player); 
  10.         } 
  11.       } 
  12.     } 
  13.   } 
  14.   //other methods skipped for brevity 

這樣那段包含對玩家帳號餘額檢測可能引發IO操作)的可能引起費時操作的代碼,被移到了鎖控制的範圍之外。注意,現在鎖僅僅被用來防止玩家人數超過桌子可容納的人數,對賬戶餘額的檢查不再是該保護措施的一部分了。

分離鎖

你可以從上面例子最後一行代碼清楚的看到:整個資料結構是由相同的鎖保護著。考慮到在這一種資料結構中可能會有數以千計的牌桌,而我們必須保護任何一張牌桌的人數不超過容量,在這樣的情況下仍然會有很高的風險出現競爭事件。

關於這個有一個簡單的辦法,就是對每一張牌桌引入分離鎖,如下面這個例子所示:

 
  1. public class GameServer { 
  2.   public Map<String, List<Player>> tables = new HashMap<String, List<Player>>(); 
  3.  
  4.   public void join(Player player, Table table) { 
  5.     if (player.getAccountBalance() > table.getLimit()) { 
  6.       List<Player> tablePlayers = tables.get(table.getId()); 
  7.       synchronized (tablePlayers) { 
  8.         if (tablePlayers.size() < 9) { 
  9.           tablePlayers.add(player); 
  10.         } 
  11.       } 
  12.     } 
  13.   } 
  14.   //other methods skipped for brevity 

現在,我們只對單一牌桌的可訪問性進行同步而不是所有的牌桌,這樣就顯著降低了出現鎖競爭的可能性。舉一個具體的例子,現在在我們的資料結構中有100個牌桌的執行個體,那麼現在發生競爭的可能性就會比之前小100倍。

使用安全執行緒的資料結構

另一個可以改善的地方就是拋棄傳統的單線程資料結構,改用被明確設計為安全執行緒的資料結構。例如,當採用ConcurrentHashMap來儲存你的牌桌執行個體時,代碼可能像下面這樣:

 
  1. public class GameServer { 
  2.   public Map<String, List<Player>> tables = new ConcurrentHashMap<String, List<Player>>(); 
  3.  
  4.   public synchronized void join(Player player, Table table) {/*Method body skipped for brevity*/} 
  5.   public synchronized void leave(Player player, Table table) {/*Method body skipped for brevity*/} 
  6.  
  7.   public synchronized void createTable() { 
  8.     Table table = new Table(); 
  9.     tables.put(table.getId(), table); 
  10.   } 
  11.  
  12.   public synchronized void destroyTable(Table table) { 
  13.     tables.remove(table.getId()); 
  14.   } 

在join()和leave()方法內部的同步塊仍然和先前的例子一樣,因為我們要保證單個牌桌資料的完整性。ConcurrentHashMap 在這點上並沒有任何協助。但我們仍然會在increateTable()destoryTable()方法中使用ConcurrentHashMap建立和銷毀新的牌桌,所有這些操作對於ConcurrentHashMap來說是完全同步的,其允許我們以並行的方式添加或減少牌桌的數量。

其他一些建議和技巧

  • 降低鎖的可見度。在上面的例子中,鎖被聲明為public對外可見),這可能會使得一些別有用心的人通過在你精心設計的監視器上加鎖來破壞你的工作。

  • 通過查看java.util.concurrent.locks 的API來看一下 有沒有其它已經實現的鎖策略,使用其改進上面的解決方案。

  • 使用原子操作。在上面正在使用的簡單遞增計數器實際上並不要求加鎖。上面的例子中更適合使用 AtomicInteger代替Integer作為計數器。

最後一點,無論你是否正在使用Plumber的自動死結檢測解決方案,還是手動從線程轉儲獲得解決辦法的資訊,都希望這篇文章可以為你解決鎖競爭的問題帶來協助。

聯繫我們

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