java - 多线程并发情况下Map.containsKey() 判断有问题
问题描述
有下面一段代码:
package test;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;public class TestContain extends Thread{ private final String key = 'key'; private final static ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();private static Object getLock(String lockName) { if (!locks.containsKey(lockName)) {//这一句会存在并发问题locks.put(lockName, new String('我是值'));System.out.println('加了一次'); } return locks.get(lockName);}@Overridepublic void run() { getLock(this.key);};public static void main(String[] args) { for (int i = 0; i < 20; i++) {new TestContain().start();; }}}
输出结果:
加了一次加了一次加了一次
表明了Map.containsKey() 在多线程的情况下会判断不准确。
这是为什么呢? 有什么方法改进呢?
问题解答
回答1:ConcurrentHashMap的doc上有一段
Retrieval operations (including <tt>get</tt>) generally do not block, so may overlap with update operations (including
<tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results of the most recently completed update operations holding upon their onset.
里面的get方法并不加锁,get方法只是拿到最新完成update的值。
所以题主方法中的locks.containsKey(lockName)没有锁来保证线程安全的。而且感觉ConcurrentHashMap的使用场景并不是用containsKey来保证更新操作只进行一次,而是用putIfAbsent来保证。
回答2:ConcurrentMap保证的是单次操作的原子性,而不是多次操作。
你的getLock函数中包含了多次操作,ConcurrentMap没法扩大它的同步范围,你需要自己实现getLock的锁。
回答3:使用putIfAbsent方法。
相关文章:
1. java固定键值转换,使用枚举实现字典?2. vim - win10无法打开markdown编辑器3. mysql - 千万数据 分页,当偏移量 原来越大时,怎么优化速度4. 如何解决tp6在zend中无代码提示5. javascript - 有没有类似高铁管家的时间选择插件6. 这是什么情况???7. python - flask学习,user_syy添加报role is invalid keyword for User.8. css - BEM 中块(Block)有木有什么标准 何时决定一个部分提取为块而不是其父级的元素呢(Element)?~9. css3 - less或者scss 颜色计算的知识应该怎么学?或者在哪里学?10. javascript - 微信网页开发从菜单进入页面后,按返回键没有关闭浏览器而是刷新当前页面,求解决?
