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

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

    ConcurrentHashMap is preferred when you can use it - though it requires at least Java 5.

    It is designed to scale well when used by multiple threads. Performance may be marginally poorer when only a single thread accesses the Map at a time, but significantly better when multiple threads access the map concurrently.

    I found a blog entry that reproduces a table from the excellent book Java Concurrency In Practice, which I thoroughly recommend.

    Collections.synchronizedMap makes sense really only if you need to wrap up a map with some other characteristics, perhaps some sort of ordered map, like a TreeMap.

提交回复
热议问题