博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ConcurrentMap.putIfAbsent(key,value) 用法讨论
阅读量:4081 次
发布时间:2019-05-25

本文共 3987 字,大约阅读时间需要 13 分钟。

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);	}

转载地址:http://uitni.baihongyu.com/

你可能感兴趣的文章
ACfly调参记录(包括ACfly-F330和ACfly-T265)
查看>>
一定记得每飞几次或者隔一天要把螺丝和浆帽拧一次,确实会松的
查看>>
《多旋翼无人飞行器嵌入式飞控开发指南》里基于FreeRTOS的无人机软件框架
查看>>
我感觉无人机借助于激光雷达实现定点悬停的效果应该好于光流才是
查看>>
思岚A1的SDK其实很好读懂,每个函数清晰明了,可以直接调用
查看>>
六角铜柱的型号
查看>>
pixhawk无GPS时可以在定高或者自稳模式下解锁起飞(见过多次别人说到)
查看>>
pixhawk(PX4)的一些论坛网站(包括中文版的PX4用户手册和PX4开发手册)
查看>>
串级 PID 为什么外环输出是内环的期望?(和我之前对串级PID的总结一样)
查看>>
APM/Pixhawk飞行日志分析入门(苍穹四轴)
查看>>
我刚刚才完全清楚GPS模块的那根杆子是怎么固定安装好的
查看>>
去github里面找找也没有别人无人机+SLAM的工程
查看>>
PX4与ROS关系以及仿真控制(键盘控制无人机)
查看>>
我对无人机重心高度的理解
查看>>
现在明白为什么无名博客里好几篇文章在讲传感器的滞后
查看>>
实际我看Pixhawk定高模式其实也是飞得很稳,飘得也不厉害
查看>>
Pixhawk解锁常见错误
查看>>
C++的模板化等等的确实比C用起来方便多了
查看>>
ROS是不是可以理解成一个虚拟机,就是操作系统之上的操作系统
查看>>
用STL algorithm轻松解决几道算法面试题
查看>>