Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "ConcurrentHashMap.putAll(...)" atomic?

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?

like image 309
Japer D. Avatar asked Dec 14 '11 23:12

Japer D.


People also ask

Is computeIfAbsent Atomic?

It's important to notice that with computeIfAbsent(), a compound operation is not necessarily atomic because updates are performed outside of the method.

What is difference between ConcurrentHashMap and HashTable?

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.

What is difference between ConcurrentHashMap and synchronized HashMap?

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.

Is ConcurrentHashMap values thread safe?

The ConcurrentHashMap operations are thread-safe. ConcurrentHashMap doesn't allow null for keys and values.


2 Answers

It's not atomic, no. According to the class documentation:

For aggregate operations such as putAll and clear, 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.

like image 156
ruakh Avatar answered Sep 23 '22 12:09

ruakh


at the top of the doc

For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.

like image 38
ratchet freak Avatar answered Sep 23 '22 12:09

ratchet freak