如何在并发 HashMap 上执行安全获取操作? (与 putIfAbsent 相同)
不好的例子,不是很线程安全(检查然后采取行动):
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;
}
这里可取的事情是不要通过同步添加、删除和获取操作来成为瓶颈。
谢谢
最佳答案
ConcurrentHashMap
上的get()
方法是原子的。由于该映射不允许空值,get()
实现“get if present”:如果结果为 null
,则 key 不存在。
关于Java ConcurrentHashMap 原子获取如果存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4353835/