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?
Same question for HashMap
.
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.
That being said, you should really make it final
.
Do we need to make the map volatile so that writes of one thread are seen by the reader threads as soon as possible?
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.
Is it possible that a put to the map in one thread is not seen or seen very late by a different thread? Same question for
HashMap
.
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