簡體   English   中英

Findbugs-調用java.util.concurrent.ConcurrentHashMap的順序可能不是原子的

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM