What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

前端 未结 19 1151
名媛妹妹
名媛妹妹 2020-11-22 11:45

I have a Map which is to be modified by several threads concurrently.

There seem to be three different synchronized Map implementations in the Java API:

    <
19条回答
  •  梦谈多话
    2020-11-22 12:09

    Synchronized Map:

    Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. Only difference between Hashtable and SynchronizedMap is that SynchronizedMap is not a legacy and you can wrap any Map to create it’s synchronized version by using Collections.synchronizedMap() method.

    ConcurrentHashMap:

    The ConcurrentHashMap class provides a concurrent version of the standard HashMap. This is an improvement on the synchronizedMap functionality provided in the Collections class.

    Unlike Hashtable and Synchronized Map, it never locks whole Map, instead it divides the map in segments and locking is done on those. It perform better if number of reader threads are greater than number of writer threads.

    ConcurrentHashMap by default is separated into 16 regions and locks are applied. This default number can be set while initializing a ConcurrentHashMap instance. When setting data in a particular segment, the lock for that segment is obtained. This means that two updates can still simultaneously execute safely if they each affect separate buckets, thus minimizing lock contention and so maximizing performance.

    ConcurrentHashMap doesn’t throw a ConcurrentModificationException

    ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it

    Difference between synchornizedMap and ConcurrentHashMap

    Collections.synchornizedMap(HashMap) will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on Map object while in case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon concurrency level and only locking particular portion instead of locking whole Map.

    ConcurrentHashMap does not allow null keys or null values while synchronized HashMap allows one null keys.

    Similar links

    Link1

    Link2

    Performance Comparison

提交回复
热议问题