问题描述
我们有一个共享的 ConcurrentHashMap
,它由2个线程读写.
We have a shared ConcurrentHashMap
which is read and written by 2 threads.
class Test {
private ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<>();
Object read() {
return map.get(object);
}
void write(Object key, Object object) {
map.put(key, object);
}
}
我们是否需要使映射可变,以便读者线程尽快看到一个线程的写入?
Do we need to make the map volatile so that writes of one thread are seen by the reader threads as soon as possible?
是否有可能在一个线程中看不到地图的放置权或在另一个线程中看到的时间太晚?
Is it possible that a put to the map in one thread is not seen or seen very late by a different thread?
与 HashMap
相同的问题.
推荐答案
如果可以将其设置为 final
,则可以这样做.如果无法将其设置为 final
,则可以,则需要将其设置为 volatile
. volatile
适用于字段分配,如果不是 final
,则可能(至少根据JMM)有可能不是一个线程写CHM字段对另一个线程可见.重申一下,这是 ConcurrentHashMap
字段分配,而不使用CHM.
If you can make it final
then do that. If you cannot make it final
then yes you would need to make it volatile
. volatile
applies to the field assignment and if it's not final
then there is a possibility (at least per the JMM) that a write of the CHM field by one thread may not be visible to another thread. To reiterate, this is the ConcurrentHashMap
field assignment and not using the CHM.
话虽如此,您应该真正做到 final
.
That being said, you should really make it final
.
如果您所说的文字是使用CHM本身的变异方法(例如 put
或 remove
)完成的,则使字段可变不会产生任何影响.所有内存可见性保证都在CHM内完成.
If the writes you speak of are done using the mutation methods of the CHM itself (like put
or remove
) you making the field volatile doesn't have an effect. All memory visibility guarantees are done within the CHM.
不适用于 ConcurrentHashMap
.如果同时使用普通的 HashMap
,请不要使用.请参阅: http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html
Not for the ConcurrentHashMap
. If you are using a plain HashMap
concurrently, don't. See: http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html
这篇关于我们是否需要使ConcurrentHashMap易变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!