zoukankan      html  css  js  c++  java
  • ConcurrentMap.putIfAbsent(key,value) 用法讨论

    http://wxl24life.iteye.com/blog/1746794


    先看一段代码:

    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. }  

     

    在某个线程做完 locale == null 的判断到真正向 map 里面 put 值这段时间,其他线程可能已经往 map 做了 put 操作,这样再做 put 操作时,同一个 key 对应的 locale 对象被覆盖掉,最终 getInstance 方法返回的同一个 key 的 locale 引用就会出现不一致的情形。所以对 Map 的 put-if-absent 操作是不安全的(thread safty)。



    故而引出了ConcurrentMap:将读与写封装为原子操作:


    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. }  
     其实基于putIfAbsent的原子性,光两句就够了:
    1.             locale = new Locale(language, country, variant);  
    2.             map.putIfAbsent(key, locale);  

    加一层判断目的有二 :

    1.像单例模式那样在外做一层判断,避免putIfAbsent无谓的执行多次

    2.避免海量的Locale对象的实例化


    (在这段代码下,仍会存在少量Locale多次实例化、putIfAbsent多次执行,试想一下这个场景:

    A线程执行null判断通过-》B线程执行null判断通过—》A线程执行putIfAbsent,将新建的对象放入-》B线程执行putIfAbsent,发现有对象了,放弃

    这个场景与map的不同在于:

    A线程执行null判断通过-》B线程执行null判断通过—》A线程执行put,将新建的对象放入-》B线程执行putIfAbsent,又将新建的对象放入


    同样是多次执行,但ConcurrentMap不会覆盖原对象,但Map会)



    但是这一段最后的返回仍有问题:(不是说这段代码的存放有问题,是返回有问题)


    还回来看这个场景:

    A线程执行null判断通过-》B线程执行null判断通过—》A线程执行putIfAbsent,将新建的对象放入-》B线程执行putIfAbsent,发现有对象了,放弃

    “B线程执行putIfAbsent,发现有对象了,放弃”,返回者Locale并非最新存放进的对象,因为它放弃了,应当返回原值。


    有两种方法:

    1.


    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 map.get(key);  
    13.     }  
    14.     // ....  
    15. }  


    看最后一句:

    return map.get(key);  



    2.利用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. }  

    1.  if (l != null) {  
    2.         locale = l;  
    3.         }  

    这一小段,如果putIfAbsent返回null,表示没有找到key,最终put的即是locale,返回locale即可

    如果返回非null,表示在

    这个并发的过程中

    A线程执行null判断通过-》B线程执行null判断通过—》A线程执行putIfAbsent,将新建的对象放入-》B线程执行putIfAbsent,发现有对象了,放弃

    A线程已经捷足先登,率先put,故新建的实例locale并非put进的对象,应当取putIfAbsent的返回值(即原值、即A线程抢先put的对象)


    两个方法比较:

    第1中方法比第2中方法多一个get操作,因此性能不如第2种方法,但是可读性更高

    rongyun 的sdk单例模式就是用的第一种方法

    	public static RongCloud getInstance(String appKey, String appSecret) {
    		if (null == rongCloud.get(appKey)) {
    			rongCloud.putIfAbsent(appKey, new RongCloud(appKey, appSecret));
    		}
    		return rongCloud.get(appKey);
    	}

  • 相关阅读:
    Java自学-数组 创建数组
    Java自学-控制流程 结束外部循环
    Java自学-控制流程 break
    Java自学-控制流程 for
    Java自学-控制流程 continue
    Java自学-控制流程 switch
    Java自学-控制流程 If
    计算机组成原理之流水线处理器
    计算机组成原理之算术逻辑单元
    计算机组成原理之指令系统
  • 原文地址:https://www.cnblogs.com/silyvin/p/9106700.html
Copyright © 2011-2022 走看看