concurrent hashMap putIfAbsent method functionality

前端 未结 2 1448
后悔当初
后悔当初 2021-02-11 09:29

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:52

    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.

提交回复
热议问题