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

前端 未结 19 1063
名媛妹妹
名媛妹妹 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:05

    ConcurrentHashMap

    • You should use ConcurrentHashMap when you need very high concurrency in your project.
    • It is thread safe without synchronizing the whole map.
    • Reads can happen very fast while write is done with a lock.
    • There is no locking at the object level.
    • The locking is at a much finer granularity at a hashmap bucket level.
    • ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.
    • ConcurrentHashMap uses multitude of locks.

    SynchronizedHashMap

    • Synchronization at Object level.
    • Every read/write operation needs to acquire lock.
    • Locking the entire collection is a performance overhead.
    • This essentially gives access to only one thread to the entire map & blocks all the other threads.
    • It may cause contention.
    • SynchronizedHashMap returns Iterator, which fails-fast on concurrent modification.

    source

提交回复
热议问题