I use CopyOnWriteArrayList
quite alot. This is especially true when
However, I will use Collections.synchronizedList()
when
This is because according to CopyOnWriteArrayList Java Doc
A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.
This is ordinarily too costly, ...
When comes to ConcurrentHashMap
, I was wondering can I still apply the same logic in choosing ConcurrentHashMap
over Collections.synchronizedMap()
?
Does ConcurrentHashMap
make a fresh copy of underlying data structure, every-time I perform write operation? Will it perform badly than Collections.synchronizedMap, if there is more write operation than read?
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.
CopyOnWriteArrayList is a concurrent Collection class introduced in Java 5 Concurrency API along with its popular cousin ConcurrentHashMap in Java.
CopyOnWriteArrayList is a thread-safe variant of ArrayList where operations which can change the ArrayList (add, update, set methods) creates a clone of the underlying array. CopyOnWriteArrayList is to be used in a Thread based environment where read operations are very frequent and update operations are rare.
Atomic operations: All operations on the ConcurrentHashMap are atomic, which means you can safely perform concurrent data access. Lock-free: The ConcurrentHashMap is designed to be lock-free, which means that there is no need to acquire a lock in order to read or write data.
No, ConcurrentHashMap
does not make a fresh copy of underlying data structure.
ConcurrentHashMap
is a segmented map, number of segments are based on concurrency level. And when you write to a segment, then it gets locked until write is complete.
ConcurrentHashMap
is almost always the right one to use as it has better performance and more useful API (you can avoid the check-then-set
thread problem) than its counterparts
It uses lock stripping for finer grained access and does not copy the map.
The only application where you should not use a ConcurrentHashMap
is when you would need to lock the map for exclusive access.
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