ConcurrentHashMap Performance and Thread safety
?? Saral Saxena ??????
?11K+ Followers | Linkedin Top Voice || Associate Director || 14+ Years in Java, Microservices, Kafka, Spring Boot, Cloud Technologies (AWS, GCP) | Agile , K8s ,DevOps & CI/CD Expert
ConcurrentHashMap provides better Performance by replacing the Hashtable's map wide lock to Segment level lock. Hashtable is not efficient beacause it uses map wide lock, it means lock is applied on map object itself, So if 2 threads tries to call hashtable.get(key),
Thread T1 calls to get() method will acquire a lock on hashtable object and then execute get() method. (Lock is on complete 'hashtable object')
Now if Thread T2 calls hashtable.get(key) method, then it will also try to acquire lock on hashtable object, but T2 will not able to acquire lock as lock on 'hashtable' is currently held by T1, So T2 waits until T1 finishes get() operation and release lock on hashtable object.
Read Operation: get(key)
Same Segment/Different Segment : Yes. Two threads T1 and T2 both can simultaneously read data from same Segment or different Segment of CHM simultaneously without blocking each other.
Write Operation: put(key, value)
Different Segment :Yes Multiple threads can write data to different Segment of CHM simultaneously without blocking each other.
Same Segment : No Multiple threads CANNOT write data to same Segment of CHM simultaneously and need to wait for one thread to come write operation and then only other write operation can be proceed.
Read-Write Operation: get and put
Say T1 is writing data in Segment 1 and T2 is reading data from same Segment 1, can read be allowed while writing operation is going on?
YES. Both operation that is T1 writing and T2 reading can be done parallely.
What data will T2 read if T1 is updating same data?Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Latest updated value present will be returned by get operation that is value updated by most recently completed update operationswill be returned.
Note: Get operations are lock free and can be performed simulateneously irrespective of other thread writing data on same or different Segment of CHM.