並行ハッシュマップで現在の操作を安全に取得するにはどうすればよいですか?(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;
}
もう1つの悪い例は次のとおりです。
public boolean setOption(String id, Object option){
if (concMap.contains(id)){
concMap.get(id).setOption(option);
return true;
}
return false;
}
ここで望ましいのは、追加、削除、および取得操作を同期してボトルネックにしないことです。
ありがとう