Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Bucket level lock and segment level lock in ConcurrentHashMap?

I gone through below link and some online video tutorials but am unable to find exact differnece between Bucket level lock and segment level lock in ConcurrentHashMap.

ConcurrentHashMap

like image 709
NPE Avatar asked Nov 30 '25 00:11

NPE


1 Answers

In Java 8 ConcurrentHashMap changed its logic to use bucket level locks instead of segment level locks.

What is the difference?

In Java 7 the map was subdivided among Segments, each of which itself is a concurrently readable hash table. Each segment contains some number of buckets inside.

The bucket itself is a list/array of key-value pairs.

The number of threads working with map in parallel was limited to the number of segments.

In Java 8 lock level was moved to a bucket level, while segments were removed (it is still in the code, but without use).

So, basically, in Java 7 inserting was locking a few buckets, in Java 8 - only one.

Another reason why it was done is that the number of threads, which are working in parallel with the map, can increase during map size increasing (more buckets - more threads). In Java 7 segments size was fixed, and it couldn't be changed without recreating a map.

like image 196
DDovzhenko Avatar answered Dec 01 '25 14:12

DDovzhenko