深入理解ConcurrentMap.putIfAbsent(key,value) 用法

深入理解ConcurrentMap.putIfAbsent(key,value) 用法

2014年10月22日 22:26:46 吳孟達 閱讀數:9904

先看一段代碼:

Java代碼  收藏代碼

  1. public class Locale {  
  2.     private final static Map<String, Locale> map = new HashMap<String,Locale>();  
  3.     public static Locale getInstance(String language, String country,  
  4.             String variant) {  
  5.         //...  
  6.         String key = some_string;  
  7.         Locale locale = map.get(key);  
  8.         if (locale == null) {  
  9.             locale = new Locale(language, country, variant);  
  10.             map.put(key, locale);  
  11.         }  
  12.         return locale;  
  13.     }  
  14.     // ....  
  15. }  

 

 這段代碼要做的事情是:

 

  1. 調用 map.get(key) 方法,判斷 map 裏面是否有該 key 對應的 value (Locale 對象)。
  2. 如果返回 null,表示 map 裏面沒有要查找的 key-value mapping。new 一個 Locale 對象,並把 new 出來的這個對象與 key 一起放入 map。
  3. 最後返回新創建的 Locale 對象

我們期望每次調用 getInstance 方法時要保證相同的 key 返回同一個 Local 對象引用。那麼,單看第一段代碼,請問它能實現這個期望麼?

 

答案是:在單線程環境下可以滿足要求,但是在多線程環境下會存在線程安全性問題,即不能保證在併發的情況相同的 key 返回同一個 Local 對象引用。

 

這是因爲在上面的代碼裏存在一個習慣被稱爲 put-if-absent 的操作 [1],而這個操作存在一個 race condition:

Java代碼  收藏代碼

  1. if (locale == null) {  
  2.     locale = new Locale(language, country, variant);  
  3.     map.put(key, locale);  
  4. }  

 因爲在某個線程做完 locale == null 的判斷到真正向 map 裏面 put 值這段時間,其他線程可能已經往 map 做了 put 操作,這樣再做 put 操作時,同一個 key 對應的 locale 對象被覆蓋掉,最終 getInstance 方法返回的同一個 key 的 locale 引用就會出現不一致的情形。所以對 Map 的 put-if-absent 操作是不安全的(thread safty)。

 

爲了解決這個問題,java 5.0 引入了 ConcurrentMap 接口,在這個接口裏面 put-if-absent 操作以原子性方法 putIfAbsent(K key, V value) 的形式存在。正如 javadoc 寫的那樣:

Java代碼  收藏代碼

  1. /** 
  2.      * If the specified key is not already associated 
  3.      * with a value, associate it with the given value. 
  4.      * This is equivalent to 
  5.      * <pre> 
  6.      *   if (!map.containsKey(key)) 
  7.      *       return map.put(key, value); 
  8.      *   else 
  9.      *       return map.get(key);</pre> 
  10.      * except that the action is performed atomically. 
  11.      * ..... 
  12.      */  

所以可以使用該方法替代上面代碼裏的操作。但是,替代的時候很容易犯一個錯誤。請看下面的代碼:

Java代碼  收藏代碼

  1. public class Locale implements Cloneable, Serializable {  
  2.     private final static ConcurrentMap<String, Locale> map = new ConcurrentHashMap<String, Locale>();  
  3.     public static Locale getInstance(String language, String country,  
  4.             String variant) {  
  5.         //...  
  6.         String key = some_string;  
  7.         Locale locale = map.get(key);  
  8.         if (locale == null) {  
  9.             locale = new Locale(language, country, variant);  
  10.             map.putIfAbsent(key, locale);  
  11.         }  
  12.         return locale;  
  13.     }  
  14.     // ....  
  15. }  

 這段代碼使用了 Map 的 concurrent 形式(ConcurrentMap、ConcurrentHashMap),並簡單的使用了語句map.putIfAbsent(key, locale) 。這同樣不能保證相同的 key 返回同一個 Locale 對象引用。

 

這裏的錯誤出在忽視了 putIfAbsent 方法是有返回值的,並且返回值很重要。依舊看 javadoc:

Java代碼  收藏代碼

  1. /** 
  2.   * @return  the previous value associated with the specified key, or 
  3.   *         <tt>null</tt> if there was no mapping for the key. 
  4.   *         (A <tt>null</tt> return can also indicate that the map 
  5.   *         previously associated <tt>null</tt> with the key, 
  6.   *         if the implementation supports null values.) 
  7.   */  

“如果(調用該方法時)key-value 已經存在,則返回那個 value 值。如果調用時 map 裏沒有找到 key 的 mapping,返回一個 null 值”

 

所以,使用 putIfAbsent 方法時切記要對返回值進行判斷。如下所示(java.util.Locale 類中的實現代碼):

Java代碼  收藏代碼

  1. public final class Locale implements Cloneable, Serializable {  
  2.     // cache to store singleton Locales  
  3.     private final static ConcurrentHashMap<String, Locale> cache = new ConcurrentHashMap<String, Locale>(32);  
  4.     static Locale getInstance(String language, String country, String variant) {  
  5.         if (language== null || country == null || variant == null) {  
  6.             throw new NullPointerException();  
  7.         }  
  8.   
  9.     StringBuilder sb = new StringBuilder();  
  10.     sb.append(language).append('_').append(country).append('_').append(variant);  
  11.     String key = sb.toString();  
  12.     Locale locale = cache.get(key);  
  13.     if (locale == null) {  
  14.         locale = new Locale(language, country, variant);  
  15.         Locale l = cache.putIfAbsent(key, locale);  
  16.         if (l != null) {  
  17.         locale = l;  
  18.         }  
  19.     }  
  20.     return locale;  
  21.     }  
  22.     // ....  
  23. }  

與前段代碼相比,增加了對方法返回值的判斷:

Java代碼  收藏代碼

  1. Locale l = cache.putIfAbsent(key, locale);    
  2. if (l != null) {    
  3.     locale = l;    
  4. }    

 

這樣可以保證併發情況下代碼行爲的準確性。

 

-------------------------------------------------

本文寫的內容源於今天閱讀 java.util.DateFormat 源碼時碰到的一個用法,更準確的說,這個用法出現在 java SE 6 的 java.util.Locale 類的 getInstance(String language, String country, String variant) 方法實現部分。

 

加之前陣子剛看過 FindBugs 的某個 ppt [2],ppt 上舉了幾個 Java 程序員容易犯錯的代碼寫法的例子,其中一個就是忽視ConcurrentMap.putIfAbsent 方法返回值的情況。

 

最後,借用 ppt 上給的關於這個錯誤的 lessons(經驗教訓):

 

  • Concurrency is tricky
  • putIfAbsent is tricky to use correctly
  • engineers at Google got it wrong more than 10% of the time
  • Unless you need to ensure a single value, just use get followed by put if not found
  • If you need to ensure a single unique value shared by all threads, use putIfAbsent and Check return value

-------------------------------------------

參考:

[1] Java Concurrency in Practice. by Brian Goetz, Tim Peierls, Joshua Bloch el.

[2] Defective Java Code: Mistakes That Matter. by William Pugh

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章