ConcurrentHashMap vs Synchronized HashMap

hello_world_infinity picture hello_world_infinity · Aug 18, 2009 · Viewed 142.7k times · Source

What is the difference between using the wrapper class, SynchronizedMap, on a HashMap and ConcurrentHashMap?

Is it just being able to modify the HashMap while iterating it (ConcurrentHashMap)?

Answer

Joey.zhgw picture Joey.zhgw · Dec 6, 2013

Synchronized HashMap

  1. Each method is synchronized using an object level lock. So the get and put methods on synchMap acquire a lock.

  2. Locking the entire collection is a performance overhead. While one thread holds on to the lock, no other thread can use the collection.

ConcurrentHashMap was introduced in JDK 5.

  1. There is no locking at the object level,The locking is at a much finer granularity. For a ConcurrentHashMap, the locks may be at a hashmap bucket level.

  2. The effect of lower level locking is that you can have concurrent readers and writers which is not possible for synchronized collections. This leads to much more scalability.

  3. ConcurrentHashMap does not throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it.

This article Java 7: HashMap vs ConcurrentHashMap is a very good read. Highly recommended.