简体   繁体   中英

Java nested ConcurrentHashMap is it thread safe?

So this is implementation ..

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 looks thread-safe

  • PutIfAbsent is atomic operation.
  • Then get inner map and putting value should be thread-safe too, as i think.

Thanks for any clarifications

In the put method, you're always creating a new ConcurrentHashMap , even if it is not needed. That is wasteful.

Also, in the put method, if a map key can be removed by another thread, the nested map could be removed between the putIfAbsent and get calls, causing a NullPointerException . Use computeIfAbsent instead:

public void put(String subKey, String key, Object value) {
    map.computeIfAbsent(subKey, k -> new ConcurrentHashMap<>())
       .put(key, value);
}

In the get method, you should not call get twice, because the value might change between first and second call. Save the value is a variable:

public Object get(String subKey, String key) {
    ConcurrentMap<String, Object> subMap = map.get(subKey);
    return subMap == null ? null : subMap.get(key);
}

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