Is the method ConcurrentHashMap.putAll(Map) supposed to be atomic?
I cannot find it in the documentation and it is not mentioned in the ConcurrentMap interface, so I guess the answer is no. I am asking it to be sure, since it wouldn't make sense if that operation wasn't atomic to be honest.
If it isn't atomic, what would be the best way to support atomic inserts of multiple items? Back to the good old synchronized?
It's important to notice that with computeIfAbsent(), a compound operation is not necessarily atomic because updates are performed outside of the method.
Hashtable is belongs to the Collection framework; ConcurrentHashMap belongs to the Executor framework. Hashtable uses single lock for whole data. ConcurrentHashMap uses multiple locks on segment level (16 by default) instead of object level i.e. whole Map . ConcurrentHashMap locking is applied only for updates.
ConcurrentHashMap allows performing concurrent read and write operation. Hence, performance is relatively better than the Synchronized Map. In Synchronized HashMap, multiple threads can not access the map concurrently. Hence, the performance is relatively less than the ConcurrentHashMap.
The ConcurrentHashMap operations are thread-safe. ConcurrentHashMap doesn't allow null for keys and values.
It's not atomic, no. According to the class documentation:
For aggregate operations such as
putAll
andclear
, concurrent retrievals may reflect insertion or removal of only some entries.
To atomicize it, you'll have to use synchronized
, yes. There's no non-blocking way to do this.
at the top of the doc
For aggregate operations such as
putAll
andclear
, concurrent retrievals may reflect insertion or removal of only some entries.
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