并发集合的包含方法是无用的吗? [英] Is concurrent collection's contain-like method useless?
本文介绍了并发集合的包含方法是无用的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
if(concurrentHashMap.containKey(key))
{
// oops,v在当前线程之后的另一个线程中被删除
/ / complete containsKey调用
值v = concurrentHashMap.get(key);
//在v上做某事//空指针异常
}
似乎并发集合的包含类方法是无用的,要解决上述问题:
Vaule v = concurrentHashMap.get(key);
if(v!= null)
{
//确定,保存v的引用
//在v
上执行操作}
我是对吗?
解决方案如注释线程中所述:否,
containsKey
不会以任何方式保持条目锁定,因此稍后调用get(key)
可能返回null
。也就是说,如果你只对布尔感兴趣 - 是地图中的键? -
此外,您还可以使用
containsKey
接口的
containsKey
是必需的,所以它不像它不会有。if(concurrentHashMap.containKey(key)) { // oops, v has been removed in another thread right after current thread // complete containKey calling Value v = concurrentHashMap.get(key); // do something on v // null pointer exception }
It seems concurrent collection's contain-like method is useless, to fix above problem:
Vaule v = concurrentHashMap.get(key); if(v != null) { // ok, hold v's reference // do something on v }
Am I right?
解决方案As stated in the comment thread: no,
containsKey
does not keep the entry locked in any way, so a later call toget(key)
might returnnull
. That said, if you're only interested in the boolean -- is the key in the map? -- and you don't need to get the key later on, thencontainsKey
is fine.Additionally,
containsKey
is required by theMap
interface, so it's not like it wouldn't be there anyway.这篇关于并发集合的包含方法是无用的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文