Is ConcurrentHashMap analogy to CopyOnWriteArrayList
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?
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.
When writing to ConcurrentHashMap
.It only locks the part of the Map, internally, that is being written to.So by this behaviour , we can eaisly see that it doesnot make the fresh copy but make changes in same copy.
So when we try to write in ConcurrentHashMap
then it means we are trying to write in any segment then it just lock that segment as well as update only that segment.So in simple words , it Never ever makes any fresh copy. So the answer of your question is NO.
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 .