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?

- 2,335
- 7
- 23
- 27
3 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.

- 202,709
- 46
- 318
- 350
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.

- 10,285
- 4
- 34
- 40
Looking at the code of PUT in ConcurrentHashMap, the implementation has atomic behavior added to it, and Java docs say:
Blockquote This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.
As I understand, it should be safe to use put method in a ConcurrentHashMap.

- 11
- 3