ConcurrentMap.putIfAbsent(key,value)

Map<String, Locale> map = new HashMap<String,Locale>();  

在单线程环境下可以满足要求,但是在多线程环境下会存在线程安全性问题,即不能保证在并发的情况相同的 key 返回同一个 Local 对象引用。

这是因为在上面的代码里存在一个习惯被称为 put-if-absent 的操作 [1],而这个操作存在一个 race condition:

  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) 的形式存在。

  1.      *   if (!map.containsKey(key)) 
  2.      *       return map.put(key, value); 
  3.      *   else 
  4.      *       return map.get(key);</pre>

所以可以使用该方法替代上面代码里的操作。但是,替代的时候很容易犯一个错误。请看下面的代码:

  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 方法是有返回值的,并且返回值很重要

“如果(调用该方法时)key-value 已经存在,则返回那个 value 值。如果调用时 map 里没有找到 key 的 mapping,返回一个 null 值”

所以,使用 putIfAbsent 方法时切记要对返回值进行判断,增加了对方法返回值的判断:

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

这样可以保证并发情况下代码行为的准确性。

猜你喜欢

转载自my.oschina.net/u/3098425/blog/1822368