What is the difference between using the wrapper class, SynchronizedMap
, on a HashMap
and ConcurrentHashMap
?
Is it just bein
Methods on SynchronizedMap
hold the lock on the object, whereas in ConcurrentHashMap
there's a concept of "lock striping" where locks are held on buckets of the contents instead. Thus improved scalability and performance.
We can achieve thread safety by using both ConcurrentHashMap and synchronisedHashmap. But there is a lot of difference if you look at their architecture.
It will maintain the lock at the object level. So if you want to perform any operation like put/get then you have to acquire the lock first. At the same time, other threads are not allowed to perform any operation. So at a time, only one thread can operate on this. So the waiting time will increase here. We can say that performance is relatively low when you are comparing with ConcurrentHashMap.
It will maintain the lock at the segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can be able to operate on ConcurrentHashMap. Moreover, read operation doesn't require a lock. So any number of threads can perform a get operation on it.
If thread1 wants to perform put operation in segment 2 and thread2 wants to perform put operation on segment 4 then it is allowed here. Means, 16 threads can perform update(put/delete) operation on ConcurrentHashMap at a time.
So that the waiting time will be less here. Hence the performance is relatively better than synchronisedHashmap.
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.
The short answer:
Both maps are thread-safe implementations of the Map
interface. ConcurrentHashMap
is implemented for higher throughput in cases where high concurrency is expected.
Brian Goetz's article on the idea behind ConcurrentHashMap
is a very good read. Highly recommended.
SynchronizedMap
and ConcurrentHashMap
are both thread safe class and can be used in multithreaded application, the main difference between them is regarding how they achieve thread safety.
SynchronizedMap
acquires lock on the entire Map instance , while ConcurrentHashMap
divides the Map instance into multiple segments and locking is done on those.
ConcurrentHashMap allows concurrent access to data. Whole map is divided into segments.
Read operation ie. get(Object key)
is not synchronized even at segment level.
But write operations ie. remove(Object key), get(Object key)
acquire lock at segment level. Only part of whole map is locked, other threads still can read values from various segments except locked one.
SynchronizedMap on the other hand, acquire lock at object level. All threads should wait for current thread irrespective of operation(Read/Write).