concurrent hashMap putIfAbsent method functionality

前端 未结 2 689
执念已碎
执念已碎 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:54

    A ConcurrentHashMap is designed so that it can be used by a large number of concurrent Threads.

    Now, if you used the methods provided by the standard Map interface you would probably write something like this

      if(!map.containsKey("something")) {
          map.put("something", "a value");
      }
    

    This looks good and seems to do the job but, it is not thread safe. So you would then think, "Ah, but I know about the synchronized keyword" and change it to this

      synchronized(map) {
          if(!map.containsKey("something")) {
              map.put("something", "a value");
          }
      }
    

    Which fixes the issue.

    Now what you have done is locked the entire map for both read and write while you check if the key exists and then add it to the map.

    This is a very crude solution. Now you could implement your own solution with double checked locks and re-locking on the key etc. but that is a lot of very complicated code that is very prone to bugs.

    So, instead you use the solution provided by the JDK.

    The ConcurrentHashMap is a clever implementation that divides the Map into regions and locks them individually so that you can have concurrent, thread safe, reads and writes of the map without external locking.

    Like all other methods in the implementation putIfAbsent locks the key's region and not the whole Map and therefore allows other things to go on in other regions in the meantime.

提交回复
热议问题