I am a new bie to the world of java and exploring the concurrent hash map, while exploring the concurrent hashmap API , I discover the putifAbsent() method
publ
ConcurrentHashMap is used when several threads may access the same map concurrently. In that case, implementing putIfAbsent() manually, like below, is not acceptable:
if (!map.containsKey(key)) {
map.put(key, value);
}
Indeed, two threads might execute the above block in parallel and enter in a race condition, where both first test if the key is absent, and then both put their own value in the map, breaking the invariants of the program.
The ConcurrentHashMap thus provides the putIfAbsent()
operation which makes sure this is done in an atomic way, avoiding the race condition.