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
.
ConcurrentHashMap is thread-safe therefore multiple threads can operate on a single object without any problem. In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level. By default, it allows 16 thread to read and write from the Map without any synchronization.
In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate.
You should use ConcurrentHashMap when you need very high concurrency in your project. It is thread safe without synchronizing the whole map . Reads can happen very fast while write is done with a lock. There is no locking at the object level.
My question is method put() in ConcurrentHashMap also atomic? Yes, The entire method invocation is performed atomically.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With