简体   繁体   English

ConcurrentHashMap.put VS ConcurrentHashMap.replace

[英]ConcurrentHashMap.put V.S. ConcurrentHashMap.replace

From the Javadoc I know ConcurrentHashMap.replace is atomic, but what about ConcurrentHashMap.put ? 从Javadoc我知道ConcurrentHashMap.replace是原子的,但是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. 如果已存在指定键下的值,则replace仅存储键值对。 The API documentation of replace explains it: 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. 除了动作以原子方式执行。

put() is inherited from class AbstractMap which ConcurrentHashMap extends. put()继承自ConcurrentHashMap扩展的类AbstractMap No particular concurrency contract is on put() . put()上没有特定的并发契约。 This inheritance allow the use of ConcurrentHashMap in a "traditional" context of a Map. 这种继承允许在Map的“传统”上下文中使用ConcurrentHashMap But no AbstractMap method is atomic. 但是没有一个AbstractMap方法是原子的。

replace() is implemented as requested by the ConcurrentMap interface. replace()是按照ConcurrentMap接口的请求实现的。 This interface require atomic operations like replace() . 此接口需要像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. 要进行原子put()操作,请使用来自相同ConcurrentMap接口的putIfAbsent()

Looking at the code of PUT in ConcurrentHashMap, the implementation has atomic behavior added to it, and Java docs say: 在ConcurrentHashMap中查看PUT的代码,实现中添加了原子行为,Java文档说:

Blockquote This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. Blockquote此类遵循与Hashtable相同的功能规范,并包含与Hashtable的每个方法对应的方法版本。

As I understand, it should be safe to use put method in a ConcurrentHashMap. 据我所知,在ConcurrentHashMap中使用put方法应该是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM