Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentHashMap locking

I have read somewhere that in ConcurrentHashMap, the whole map object is not locked and instead a lock is made on a portion of the Map.

Can somebody elaborate when does locking come into the picture?

Is it right that while reading the Map there is no locking involved in it but while updating it only locking is used?

like image 321
Anand Avatar asked May 14 '12 18:05

Anand


Video Answer


2 Answers

Yes, ConcurrentHashMap uses a multitude of locks (by default, 16 of them), each lock controls one segment of the hash.

When setting data in a particular segment, the lock for that segment is obtained.

When getting data, a volatile read is used. If the volatile read results in a miss, then the lock for the segment is obtained for a last attempt at a successful read.

like image 160
Tim Bender Avatar answered Sep 30 '22 08:09

Tim Bender


Locking is minimized as much as possible while still being thread-safe.

To explain "part of the Map is locked", this means that when updating, only a "1/concurrencyLevel" of the Map (based on a hash of the key) is locked. This means that two updates can still simultaneously execute safely if they each affect separate "buckets", thus minimizing lock contention and so maximizing performance.

More importantly, trust the JDK implementation - you shouldn't have to worry about implementation details in the JDK (for one thing, it may change from release to release). Rather, just focus on writing your code.

like image 37
Bohemian Avatar answered Sep 30 '22 09:09

Bohemian