ConcurrentHashMap put vs putIfAbsent

后端 未结 2 1970
既然无缘
既然无缘 2021-02-05 09:32

Java Docs says that, putIfAbsent is equivalent to

   if (!map.containsKey(key)) 
      return map.put(key, value);
   else
      return map.get(key         


        
2条回答
  •  悲&欢浪女
    2021-02-05 09:58

    Your code will throw an NPE if the key was not previously in the map.

    Other than that, although this is a reasonable idea, it will not work in a "concurrent" environment. The reason the putIfAbsent() method was added was so that the map could manage the atomicity of the operation using whatever underlying support it is using to make the operations thread-safe. In your implementation, 2 different callers could end of stepping on each other (the first replaces an expired value with a new one, and the second immediately replaces the first new one with a second new one).

提交回复
热议问题