ConcurrentHashMap.put V.S. ConcurrentHashMap.replace

Zhao Yi picture Zhao Yi · Aug 15, 2012 · Viewed 8.2k times · Source

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?

Answer

Jesper picture Jesper · Aug 15, 2012

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.