Thursday 24 January 2019

ConcurrentHashMap vs Synchronized HashMap

https://stackoverflow.com/questions/1291836/concurrenthashmap-vs-synchronized-hashmap/2929410

  • Both maps are thread-safe implementations of the Mapinterface. ConcurrentHashMap is implemented for higher throughput in cases where high concurrency is expected.
  • ConcurrentHashMap does not allow null keys or null values while synchronized HashMap allows one null key.

Answer 1:
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.
Answer 2:

ConcurrentHashMap uses finer-grained locking mechanism known as lock stripping to allow greater degree of shared access. Due to this it provides better concurrency and scalability.
Also iterators returned for ConcurrentHashMap are weakly consistent instead of fail fast technique used by Synchronized HashMap.
Answer 3:
ConcurrentHashMap :
1)Both maps are thread-safe implementations of the Map interface.
2)ConcurrentHashMap is implemented for higher throughput in cases where high concurrency is expected.
3) There is no locking in object level.
Synchronized Hash Map:
1) Each method is synchronized using an object level lock.

No comments:

Post a Comment

40 Latest Interview Questions and Answers on Spring, Spring MVC, and Spring Boot

  40 Latest Interview Questions and Answers on Spring, Spring MVC, and Spring Boot 1. What is Tight Coupling? When a class (ClassA) is depen...