ConcurrentHashMap.put V.S. ConcurrentHashMap.replace

From Javadoc, I know that ConcurrentHashMap.replace is atomic, but what about ConcurrentHashMap.put ? I see that they are implemented differently in the source code, but I cannot understand their differences. Any gurus to give some recommendations on how to use these two methods?

+6
source share
3 answers

They are functionally different. replace only stores a key-value pair if there was already a value stored under the specified key. The API replace documentation explains this:

Replaces an entry for a key only if some value is currently displayed. It is equivalent

 if (map.containsKey(key)) { return map.put(key, value); } else return null; 

except that the action is atomic.

+11
source

put() inherited from the AbstractMap class, which ConcurrentHashMap continues. The specific concurrency contract is not specified by put() . This inheritance allows the use of ConcurrentHashMap in the "traditional" Map context. But the AbstractMap method is not atomic.

replace() is implemented at the request of the ConcurrentMap interface. This interface requires atomic operations such as replace() . Only the methods of this interface should be used in code with simultaneous use.

To have the atomic put() operation, use putIfAbsent() coming from the same ConcurrentMap interface.

+2
source

Looking at the PUT code in ConcurrentHashMap, the implementation adds atomic behavior to it, and Java docs say:

Blockquote This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each Hashtable method.

As I understand it, it should be safe to use the put method in ConcurrentHashMap.

0
source

Source: https://habr.com/ru/post/922922/


All Articles