![](/img/trans.png)
[英]Is ConcurrentHashMap's computeIfAbsent thread safe, when nested?
[英]Java nested ConcurrentHashMap is it thread safe?
所以这是实现..
public ConcurrentMap<String , ConcurrentMap<String, Object>> map = new ConcurrentHashMap<>();
public void put(String subKey, String key, Object value) {
map.putIfAbsent(subKey, new ConcurrentHashMap<>());
map.get(subKey).put(key, value);
}
public Object get(String subKey, String key) {
return map.get(subKey) == null ? null : map.get(subKey).get(key);
}
看起来很线程安全
感谢您的澄清
在put
方法中,即使不需要它,也始终在创建一个新的ConcurrentHashMap
。 那是浪费。
同样,在put
方法中,如果可以通过另一个线程删除映射键,则可以在putIfAbsent
和get
调用之间删除嵌套的映射,从而导致NullPointerException
。 改用computeIfAbsent
:
public void put(String subKey, String key, Object value) {
map.computeIfAbsent(subKey, k -> new ConcurrentHashMap<>())
.put(key, value);
}
在get
方法中,您不应调用get
两次,因为该值可能在第一次调用和第二次调用之间发生变化。 保存值是一个变量:
public Object get(String subKey, String key) {
ConcurrentMap<String, Object> subMap = map.get(subKey);
return subMap == null ? null : subMap.get(key);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.