![](/img/trans.png)
[英]How to resolve the findbug Sequence of calls to java.util.concurrent.ConcurrentHashMap may not be atomic
[英]Findbugs - Sequence of calls to java.util.concurrent.ConcurrentHashMap may not be atomic
我的项目中有以下代码
// Declaration
private ConcurrentHashMap<Long, ConcurrentHashMap<String, Object>> instanceSpecificBeanMap = new ConcurrentHashMap<>();
地图的使用
ConcurrentHashMap<String, Object> beanMapForInstance = instanceSpecificBeanMap.get(currentInstanceId);
Object beanObject = null;
if(beanMapForInstance == null){
synchronized (initLockObject) {
beanMapForInstance = instanceSpecificBeanMap.get(currentInstanceId);
if(beanMapForInstance == null){
beanMapForInstance = new ConcurrentHashMap<>();
instanceSpecificBeanMap.put(currentInstanceId, beanMapForInstance);
}
}
}
我认为上述操作是原子的,尽管findbugs将其显示为问题? 我在这里想念什么吗?
编辑
beanMapForInstance
仅可从此类访问。 没有其他类可以访问此变量。
另外,目前我们正在使用Java 7
使用putIfAbsent
方法。 如果给定键不存在新值,则恰恰是打算在映射中自动添加一个新值。
ConcurrentHashMap<String, Object> newMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String, Object> beanMapForInstance = instanceSpecificBeanMap.putIfAbsent(currentInstanceId, newMap);
if (beanMapForInstance == null) {
beanMapForInstance = newMap;
}
(... work with beanMapForInstance ...)
您可以使用Java 8中的computeIfAbsent
简化此过程并解决问题:
ConcurrentHashMap<String, Object> beanMapForInstance =
instanceSpecificBeanMap.computeIfAbsent(
currentInstanceId,
k -> new ConcurrentHashMap<>() // might need explicit generics
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.