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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With