如果在并行哈希映射上进行当前操作,如何执行安全获取? (喜欢的putIfAbsent同样的事情)Java ConcurrentHashMap原子获得如果存在
不好的例子,不是很线程安全(检查然后采取行动的情况):
ConcurrentMap<String, SomeObject> concMap = new ...
//... many putIfAbsent and remove operations
public boolean setOption(String id, Object option){
SomeObject obj = concMap.get(id);
if (obj != null){
//what if this key has been removed from the map?
obj.setOption(option);
return true;
}
// in the meantime a putIfAbsent may have been called on the map and then this
//setOption call is no longer correct
return false;
}
另一个不好的例子是:
public boolean setOption(String id, Object option){
if (concMap.contains(id)){
concMap.get(id).setOption(option);
return true;
}
return false;
}
这里的希望的事情就是不是通过同步它们来添加,删除和获取操作的瓶颈。
感谢
我不明白你对“这个setOption调用”的评论 - 你指哪个setOption方法?你的代码中有两个。 – 2010-12-04 14:02:06
这只是存储在地图中的一些通用对象的泛型集方法。 – cdmihai 2010-12-04 14:06:15
如果键值对可能从地图中删除,则您的第二个示例可能有缺陷。这可能发生在包含测试和get之间。 – 2010-12-04 14:26:30