ConcurrentHashMap 是否可以有超过 32 个锁
我读到 ConcurrentHashMap 在多线程中比 Hashtable 效果更好,因为它具有存储桶级别的锁而不是映射范围的锁。每张地图最多可以有 32 个锁。想知道为什么是32以及为什么不能超过32个锁。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您谈论的是 Java ConcurrentHashMap,那么限制是 任意:
如果您阅读源代码,它就会变得清楚最大段数为 2^16,这应该足以满足近期任何可能的需求。
您可能一直在考虑某些替代实验性实现,例如 这个:
请注意,一般来说,当超过 32 个线程尝试更新单个
ConcurrentHashMap
时,同步效率以外的因素通常会成为瓶颈。If you're talking about the Java
ConcurrentHashMap
, then the limit is arbitrary: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:
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
.默认值不是 32,而是 16。您可以使用 构造函数参数
并发级别
:所以你可以这样做:
将其更改为64。默认值是(从Java 6u17开始):
initialCapacity:16;
loadFactory
:0.75f;并发级别
:16。The default isn't 32, it's 16. And you can override it with the constructor argument
concurrency level
:so you can do:
to change it to 64. The defaults are (as of Java 6u17):
initialCapacity
: 16;loadFactory
: 0.75f;concurrencyLevel
: 16.根据
ConcurrentHashMap
的来源,允许的最大值是65536
:According to the source of
ConcurrentHashMap
, the maximum allowed is65536
:要使用所有默认并发级别 16,您需要有 16 个核心同时使用该映射。如果您有 32 个核心,仅在 25% 的时间内使用该映射,则一次将仅使用 16 个段中的 8 个。
总之,您需要有很多核心都使用相同的映射,并且不执行任何其他操作。真实的程序通常会执行除访问一张映射之外的其他操作。
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.