如果在並行哈希映射上進行當前操作,如何執行安全獲取? (喜歡的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