如果在并发哈希映射上存在操作,您如何执行安全获取?(与 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;
}
这里的可取之处是不要通过同步添加、删除和获取操作来限制它们。
谢谢