Search code examples
javaconcurrencyjava.util.concurrentconcurrenthashmap

Need simple explanation how "lock striping" works with ConcurrentHashMap


According to Java Concurrency in Practice, chapter 11.4.3 says:

Lock splitting can sometimes be extended to partition locking on a variablesized set of independent objects, in which case it is called lock striping. For example, the implementation of ConcurrentHashMap uses an array of 16 locks, each of which guards 1/16 of the hash buckets; bucket N is guarded by lock N mod 16.

I still have problems to understand and visualize the lock striping and buckets mechanism. Can someone explain this with good understanding words :)

Thanks in advance.


Solution

  • The hash map is built on an array, where the hash function maps an object to an element in the underlying array. Let's say the underlying array has 1024 elements - ConcurrentHashMap actually turns this into 16 different sub-arrays of 64 elements, e.g. {0, 63}, {64, 127}, etc. Each sub-array has its own lock, so modifying the {0, 63} sub-array doesn't impact the {64, 127} sub-array - one thread can write to the first sub-array while another thread writes to the second sub-array.