Posts

Showing posts with the label Java - SynchronizedHashMap and ConcurrentHashMap

Performance of HashMap, HashTable, SynchronizedHashMap and ConcurrentHashMap

Synchronized  HashMap : Each method is synchronized using an object level lock. So the get and put methods on synchMap acquire a lock. 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. 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. 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. ConcurrentHashMap  does not throw a  ConcurrentModificationException  if one thread tries to modify it while another is iterating over it. I highly recommend to follow the below link. Clearly explained about the difference in the performance between HashMap, HashTable, SynchronizedHashMap and ConcurrentHashMap when