从 Javadoc 我知道 ConcurrentHashMap.replace
是原子的,但是 ConcurrentHashMap.put
呢?我看到它们在源代码中的实现方式不同,但我无法弄清楚它们的区别。任何大师都可以提供一些有关如何使用这两种方法的指南吗?
最佳答案
它们在功能上是不同的。 replace
仅在指定键下已存储值时才存储键值对。 replace
的API文档是这样解释的:
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.
关于java - ConcurrentHashMap.put V.S. ConcurrentHashMap.replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11967479/