cdm*_*hai 4 java concurrenthashmap
如何在并发哈希映射上执行安全获取操作?(与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;
}
Run Code Online (Sandbox Code Playgroud)
另一个糟糕的例子是:
public boolean setOption(String id, Object option){
if (concMap.contains(id)){
concMap.get(id).setOption(option);
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这里需要的是不要通过同步来阻止添加,删除和获取操作.
谢谢
a上的get()方法ConcurrentHashMap是原子的.由于该映射不允许空值,因此get()实现"get if present":如果结果为null,则该键不存在.
| 归档时间: |
|
| 查看次数: |
7524 次 |
| 最近记录: |