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

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

    You are right about HashTable, you can forget about it.

    Your article mentions the fact that while HashTable and the synchronized wrapper class provide basic thread-safety by only allowing one thread at a time to access the map, this is not 'true' thread-safety since many compound operations still require additional synchronization, for example:

    synchronized (records) {
      Record rec = records.get(id);
      if (rec == null) {
          rec = new Record(id);
          records.put(id, rec);
      }
      return rec;
    }
    

    However, don't think that ConcurrentHashMap is a simple alternative for a HashMap with a typical synchronized block as shown above. Read this article to understand its intricacies better.

提交回复
热议问题