Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashMap.put V.S. ConcurrentHashMap.replace

From the Javadoc I know ConcurrentHashMap.replace is atomic, but what about ConcurrentHashMap.put? I see they are differently implemented in the source code but I'm not able to figure out their differences. Any gurus to give some guidelines about how to use these two methods?

like image 717
Zhao Yi Avatar asked Aug 15 '12 10:08

Zhao Yi


2 Answers

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

Replaces the entry for a key only if currently mapped to some value. This is equivalent to

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

except that the action is performed atomically.

like image 185
Jesper Avatar answered Sep 28 '22 19:09

Jesper


put() is inherited from class AbstractMap which ConcurrentHashMap extends. No particular concurrency contract is on put(). This inheritance allow the use of ConcurrentHashMap in a "traditional" context of a Map. But no AbstractMap method is atomic.

replace() is implemented as requested by the ConcurrentMap interface. This interface require atomic operations like replace(). Only methods of this interface are to be used in a concurrent-aware code.

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

like image 26
Jérôme Radix Avatar answered Sep 28 '22 20:09

Jérôme Radix