国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

ConcurrentMap.putIfAbsent(key,value) 用法討論

2019-11-11 01:01:10
字體:
來源:轉載
供稿:網友

ConcurrentMap.putIfAbsent(key,value) 等價于下面代碼,只不過下面代碼不是線程安全的,putIfAbsent是線程安全的

if(!map.containsKey(key))	return map.put(key,value);else	return map.get(key)

先看一段代碼:

java代碼  收藏代碼public class Locale {      PRivate final static Map<String, Locale> map = new HashMap<String,Locale>();      public static Locale getInstance(String language, String country,              String variant) {          //...          String key = some_string;          Locale locale = map.get(key);          if (locale == null) {              locale = new Locale(language, country, variant);              map.put(key, locale);          }          return locale;      }      // ....  }  

 

 這段代碼要做的事情是:

 

調用 map.get(key) 方法,判斷 map 里面是否有該 key 對應的 value (Locale 對象)。如果返回 null,表示 map 里面沒有要查找的 key-value mapping。new 一個 Locale 對象,并把 new 出來的這個對象與 key 一起放入 map。最后返回新創建的 Locale 對象我們期望每次調用 getInstance 方法時要保證相同的 key 返回同一個 Local 對象引用。那么,單看第一段代碼,請問它能實現這個期望么?答案是:在單線程環境下可以滿足要求,但是在多線程環境下會存在線程安全性問題,即不能保證在并發的情況相同的 key 返回同一個 Local 對象引用。這是因為在上面的代碼里存在一個習慣被稱為 put-if-absent 的操作 [1],而這個操作存在一個 race condition:Java代碼  收藏代碼if (locale == null) {      locale = new Locale(language, country, variant);      map.put(key, locale);  }   因為在某個線程做完 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代碼  收藏代碼/**      * If the specified key is not already associated      * with a value, associate it with the given value.      * This is equivalent to      * <pre>      *   if (!map.containsKey(key))      *       return map.put(key, value);      *   else      *       return map.get(key);</pre>      * except that the action is performed atomically.      * .....      */  所以可以使用該方法替代上面代碼里的操作。但是,替代的時候很容易犯一個錯誤。請看下面的代碼:Java代碼  收藏代碼public class Locale implements Cloneable, Serializable {      private final static ConcurrentMap<String, Locale> map = new ConcurrentHashMap<String, Locale>();      public static Locale getInstance(String language, String country,              String variant) {          //...          String key = some_string;          Locale locale = map.get(key);          if (locale == null) {              locale = new Locale(language, country, variant);              map.putIfAbsent(key, locale);          }          return locale;      }      // ....  }   這段代碼使用了 Map 的 concurrent 形式(ConcurrentMap、ConcurrentHashMap),并簡單的使用了語句map.putIfAbsent(key, locale) 。這同樣不能保證相同的 key 返回同一個 Locale 對象引用。這里的錯誤出在忽視了 putIfAbsent 方法是有返回值的,并且返回值很重要。依舊看 javadoc:Java代碼  收藏代碼/**   * @return  the previous value associated with the specified key, or   *         <tt>null</tt> if there was no mapping for the key.   *         (A <tt>null</tt> return can also indicate that the map   *         previously associated <tt>null</tt> with the key,   *         if the implementation supports null values.)   */  “如果(調用該方法時)key-value 已經存在,則返回那個 value 值。如果調用時 map 里沒有找到 key 的 mapping,返回一個 null 值”所以,使用 putIfAbsent 方法時切記要對返回值進行判斷。如下所示(java.util.Locale 類中的實現代碼):Java代碼  收藏代碼public final class Locale implements Cloneable, Serializable {      // cache to store singleton Locales      private final static ConcurrentHashMap<String, Locale> cache = new ConcurrentHashMap<String, Locale>(32);      static Locale getInstance(String language, String country, String variant) {          if (language== null || country == null || variant == null) {              throw new NullPointerException();          }        StringBuilder sb = new StringBuilder();      sb.append(language).append('_').append(country).append('_').append(variant);      String key = sb.toString();      Locale locale = cache.get(key);      if (locale == null) {          locale = new Locale(language, country, variant);          Locale l = cache.putIfAbsent(key, locale);          if (l != null) {          locale = l;          }      }      return locale;      }      // ....  }  與前段代碼相比,增加了對方法返回值的判斷:Java代碼  收藏代碼Locale l = cache.putIfAbsent(key, locale);    if (l != null) {        locale = l;    }    這樣可以保證并發情況下代碼行為的準確行。-------------------------------------------------

本文寫的東西源于今天閱讀 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 trickyputIfAbsent is tricky to use correctlyengineers at Google got it wrong more than 10% of the timeUnless you need to ensure a single value, just use get followed by put if not foundIf you need to ensure a single unique value shared by all threads, use putIfAbsent and Check return value

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 措勤县| 家居| 曲麻莱县| 神池县| 恩平市| 肥东县| 青神县| 宽城| 平和县| 织金县| 宁蒗| 深泽县| 山阳县| 宜宾市| 青州市| 溧阳市| 交口县| 南京市| 怀来县| 周至县| 绍兴市| 沁水县| 安多县| 盘锦市| 石屏县| 山西省| 剑川县| 沽源县| 阿尔山市| 霍山县| 浦北县| 拜城县| 贺兰县| 贞丰县| 枣阳市| 时尚| 德令哈市| 六安市| 滁州市| 红原县| 额敏县|