concurrent hashMap putIfAbsent method functionality

前端 未结 2 679
执念已碎
执念已碎 2021-02-11 09:13

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         


        
2条回答
  •  遥遥无期
    2021-02-11 09:40

    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.

提交回复
热议问题