Is ConcurrentHashMap analogy to CopyOnWriteArrayList

I use CopyOnWriteArrayList quite alot. This is especially true when

  • Threads perform a lot of read
  • Threads perform a little of write
  • However, I will use Collections.synchronizedList() when

  • Threads perform a little of read
  • Threads perform a lot of write
  • 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 .

    链接地址: http://www.djcxy.com/p/76110.html

    上一篇: 是否有可以排序的CopyOnWriteArrayList的替代方法?

    下一篇: ConcurrentHashMap类似于CopyOnWriteArrayList