简体   繁体   中英

Findbugs - Sequence of calls to java.util.concurrent.ConcurrentHashMap may not be atomic

I have following code in my project

// Declaration

private ConcurrentHashMap<Long, ConcurrentHashMap<String, Object>> instanceSpecificBeanMap = new ConcurrentHashMap<>();

Use of map

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);
            }
        }
    }

I think above operation is atomic, although findbugs is showing it as issue? am I missing something here?

EDIT

beanMapForInstance is accessed from this class only. No other class has access to this variable.

Also, Currently we are using Java 7

Use the putIfAbsent method. It is precisely intended to atomically put a new value in the map if none exist for the given key.

ConcurrentHashMap<String, Object> newMap = new ConcurrentHashMap<>();
ConcurrentHashMap<String, Object> beanMapForInstance = instanceSpecificBeanMap.putIfAbsent(currentInstanceId, newMap);
if (beanMapForInstance == null) {
    beanMapForInstance = newMap;
}
(... work with beanMapForInstance ...)

You can simplify this and solve the problem using computeIfAbsent from Java 8:

ConcurrentHashMap<String, Object> beanMapForInstance = 
        instanceSpecificBeanMap.computeIfAbsent(
            currentInstanceId, 
            k -> new ConcurrentHashMap<>()  // might need explicit generics
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM