nits.kk nits.kk - 1 year ago 32
Java Question

How ConcurrenthashMap manages if Concurrency level is HIGHER than the number of Buckets?

The

ConcurrentHashMap
uses segment level locking mechanism for supporting concurrent modifications. It has three basic parameters


  • Number of Buckets. (Default initial size = 16)

  • Concurrency Level. (Default size = 16)

  • Load Factor.(Default size = 0.75)



In default case we have Single Lock per Bucket. If the number of buckets are made as 32 then we will have Single Lock per Two Buckets.

How is it managed if number of buckets are Less than the Concurrency Level, i.e. if

Map cMap = new ConcurrentHashMap(16,1,32);


Usually a bucket uses a Collection (Linked List) for the items with Hash-codes colliding in same bucket. Do we have in above case Two Locks per Bucket, if yes then how it is managed, (does half of the collection in a bucket uses one lock and other half uses second lock ?)

I have searched and was able to see the answers if the
ConcurrentHashMap
is resized to have more buckets than the number of Locks but I was not able to get an answer what if it was the reverse case, i.e :

How ConcurrenthashMap manages if Concurrency level is HIGHER than the number of Buckets ?

Answer Source

This code in the constructor should answer your question:

if (initialCapacity < concurrencyLevel)   // Use at least as many bins
    initialCapacity = concurrencyLevel;   // as estimated threads

See also the documentation:

concurrencyLevel the estimated number of concurrently updating threads. The implementation may use this value as a sizing hint.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download