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


轉自:http://blog.csdn.net/exceptional_derek/article/details/40384659

先看一段代碼:

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. }    
 
這樣可以保證並發情況下代碼行為的准確性。
 
-------------------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM