Is ConcurrentHashMap totally safe? Is ConcurrentHashMap totally safe? multithreading multithreading

Is ConcurrentHashMap totally safe?


The get() method is thread-safe, and the other users gave you useful answers regarding this particular issue.

However, although ConcurrentHashMap is a thread-safe drop-in replacement for HashMap, it is important to realize that if you are doing multiple operations you may have to change your code significantly. For example, take this code:

if (!map.containsKey(key))    return map.put(key, value);else   return map.get(key);

In a multi-thread environment, this is a race condition. You have to use the ConcurrentHashMap.putIfAbsent(K key, V value) and pay attention to the return value, which tells you if the put operation was successful or not. Read the docs for more details.


Answering to a comment that asks for clarification on why this is a race condition.

Imagine there are two threads A, B that are going to put two different values in the map, v1 and v2 respectively, having the same key. The key is initially not present in the map. They interleave in this way:

  • Thread A calls containsKey and finds out that the key is not present, but is immediately suspended.
  • Thread B calls containsKey and finds out that the key is not present, and has the time to insert its value v2.
  • Thread A resumes and inserts v1, "peacefully" overwriting (since put is threadsafe) the value inserted by thread B.

Now thread B "thinks" it has successfully inserted its very own value v2, but the map contains v1. This is really a disaster because thread B may call v2.updateSomething() and will "think" that the consumers of the map (e.g. other threads) have access to that object and will see that maybe important update ("like: this visitor IP address is trying to perform a DOS, refuse all the requests from now on"). Instead, the object will be soon garbage collected and lost.


It is thread-safe. However, the way it is being thread-safe may not be what you expect. There are some "hints" you can see from:

This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details

To know the whole story in a more complete picture, you need to be aware of the ConcurrentMap interface.

The original Map provides some very basic read/update methods. Even I was able to make a thread-safe implementation of Map; there are lots of cases that people cannot use my Map without considering my synchronization mechanism. This is a typical example:

if (!threadSafeMap.containsKey(key)) {   threadSafeMap.put(key, value);}

This piece of code is not thread-safe, even though the map itself is. Two threads calling containsKey() at the same time could think there is no such key they both therefore insert into the Map.

In order to fix the problem, we need to do extra synchronization explicitly. Assume the thread-safety of my Map is achieved by synchronized keywords, you will need to do:

synchronized(threadSafeMap) {    if (!threadSafeMap.containsKey(key)) {       threadSafeMap.put(key, value);    }}

Such extra code needs you to know about the "synchronization details" of the map. In the above example, we need to know that the synchronization is achieved by "synchronized".

ConcurrentMap interface take this one step further. It defines some common "complex" actions that involves multiple access to map. For example, the above example is exposed as putIfAbsent(). With these "complex" actions, users of ConcurrentMap (in most case) don't need to synchronise actions with multiple access to the map. Hence, the implementation of Map can perform more complicated synchronization mechanism for better performance. ConcurrentHashhMap is a good example. Thread-safety is in fact maintained by keeping separate locks for different partitions of the map. It is thread-safe because concurrent access to the map will not corrupt the internal data structure, or cause any update lost unexpected, etc.

With all the above in mind, the meaning of Javadoc will be clearer:

"Retrieval operations (including get) generally do not block" because ConcurrentHashMap is not using "synchronized" for its thread-safety. The logic of get itself takes care of the thread-safeness; and If you look further in the Javadoc:

The table is internally partitioned to try to permit the indicated number of concurrent updates without contention

Not only is retrieval non-blocking, even updates can happen concurrently. However, non-blocking/concurrent-updates does not means that it is thread-UNsafe. It simply means that it is using some ways other than simple "synchronized" for thread-safety.

However, as the internal synchronization mechanism is not exposed, if you want to do some complicated actions other than those provided by ConcurrentMap, you may need to consider changing your logic, or consider not using ConcurrentHashMap. For example:

// only remove if both key1 and key2 existsif (map.containsKey(key1) && map.containsKey(key2)) {    map.remove(key1);    map.remove(key2);}


ConcurrentHashmap.get() is thread-safe, in the sense that

  • It will not throw any exception, including ConcurrentModificationException
  • It will return a result that was true at some (recent) time in past. This means that two back-to-back calls to get can return different results. Of course, this true of any other Map as well.