如果地图还没有,我需要为地图添加一些价值。键-> 值(如果已设置)应始终位于两个集合中(即put
应以原子方式发生在两个映射中)。我试图按如下方式实现这一点:
private final ConcurrentMap<String, Object> map1 = new ConcurrentHashMap<String, Object>();
private final ConcurrentMap<String, Object> map2 = new ConcurrentHashMap<String, Object>();
public Object putIfAbsent(String key) {
Object retval = map1.get(key);
if (retval == null) {
synchronized (map1) {
retval = map1.get(key);
if (retval == null) {
Object value = new Object(); //or get it somewhere
synchronized (map2) {
map1.put(key, value);
map2.put(key, new Object());
}
retval = value;
}
}
}
return retval;
}
public void doSomething(String key) {
Object obj1 = map1.get(key);
Object obj2 = map2.get(key);
//do smth
}
这在所有情况下都能正常工作吗?谢谢