https://stackoverflow.com/questions/1291836/concurrenthashmap-vs-synchronized-hashmap/2929410
Read more: https://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.html#ixzz5dYro4Lri
- Both maps are thread-safe implementations of the
Map
interface.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.
Read more: https://javarevisited.blogspot.com/2011/04/difference-between-concurrenthashmap.html#ixzz5dYro4Lri
Answer 1:
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 aConcurrentModificationException
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