Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have more than 32 locks in ConcurrentHashMap

I read ConcurrentHashMap works better in multi threading than Hashtable due to having locks at bucket level rather than map wide lock. It is at max 32 locks possible per map. Want to know why 32 and why not more than 32 locks.

like image 995
DKSRathore Avatar asked Nov 22 '09 15:11

DKSRathore


2 Answers

If you're talking about the Java ConcurrentHashMap, then the limit is arbitrary:

Creates a new map with the same mappings as the given map. The map is created with a capacity of 1.5 times the number of mappings in the given map or 16 (whichever is greater), and a default load factor (0.75) and concurrencyLevel (16).

If you read the source code it becomes clear that the maximum number of segments is 2^16, which should be more than sufficient for any conceivable need in the immediate future.

You may have been thinking of certain alternative experimental implementations, like this one:

This class supports a hard-wired preset concurrency level of 32. This allows a maximum of 32 put and/or remove operations to proceed concurrently.

Note that in general, factors other than synchronization efficiency are usually the bottlenecks when more than 32 threads are trying to update a single ConcurrentHashMap.

like image 130
John Feminella Avatar answered Oct 21 '22 16:10

John Feminella


The default isn't 32, it's 16. And you can override it with the constructor argument concurrency level:

public ConcurrentHashMap(int initialCapacity,
                         float loadFactor,
                         int concurrencyLevel)

so you can do:

Map<String, String> map = new ConcurrentHashmap<String, String)(128, 0.75f, 64);

to change it to 64. The defaults are (as of Java 6u17):

  • initialCapacity: 16;
  • loadFactory: 0.75f;
  • concurrencyLevel: 16.
like image 32
cletus Avatar answered Oct 21 '22 15:10

cletus