The ConcurrentHashMap is thread safe without locking the entire table but it doesn't remove the race conditions like if we query for a key and at that time the key is not there, so in the next instruction we add the key's entry to the map. Between the two things, any other thread may have added the key and the user will inadvertently replace that with his own entry.

That could be avoided by putting the 2 statements in a synchronize block, though this particular race condition can be avoided using putIfAbsent. But my point is that we have to use our own synchronizations in the case of ConcurrentHashMap too, when putIfAbsent is not suffiecient. Is that right ?

7 Years
Discussion Span
Last Post by stephen84s

Now if I use the correct wordings, a ThreadSafe class basically guarantees that any operations performed on it would not cause the data in it to get corrupted. This is what the ConcurrentHashMap guarantees, but the situation you are talking about is performing two separate operations atomically on a ConcurrentHashMap, hence you need to put the two operations in a synchronized block, so that no other operation (from any other thread) is slotted between them.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.