开发者

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 开发者_StackOverflow中文版is at max 32 locks possible per map. Want to know why 32 and why not more than 32 locks.


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.


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.


According to the source of ConcurrentHashMap, the maximum allowed is 65536:

/**
 * The maximum number of segments to allow; used to bound
 * constructor arguments.
 */
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative

public ConcurrentHashMap(int initialCapacity,
                         float loadFactor, int concurrencyLevel) {
    if (concurrencyLevel > MAX_SEGMENTS)
        concurrencyLevel = MAX_SEGMENTS;


To use all the default concurrency level of 16 you need to have 16 cores using the map at the same moment. If you have 32 cores only using the map 25% of the time then only 8 of 16 segments will be used at once.

In summary, you need to have a lot of cores all using the same map and doing nothing much else. Real programs usually do something other than access one map.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜