java ConcurrentHashMap 锁定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10589103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ConcurrentHashMap locking
提问by Anand
I have read somewhere that in ConcurrentHashMap
, the whole map object is not locked and instead a lock is made on a portion of the Map.
我在 中的某处读到过ConcurrentHashMap
,整个地图对象没有被锁定,而是在地图的一部分上进行了锁定。
Can somebody elaborate when does locking come into the picture?
有人可以详细说明锁定何时出现?
Is it right that while reading the Map there is no locking involved in it but while updating it only locking is used?
在读取 Map 时没有涉及锁定但在更新它时只使用锁定是正确的吗?
回答by Tim Bender
Yes, ConcurrentHashMap
uses a multitude of locks (by default, 16 of them), each lock controls one segment of the hash.
是的,ConcurrentHashMap
使用多个锁(默认情况下,其中 16 个),每个锁控制哈希的一部分。
When setting data in a particular segment, the lock for that segment is obtained.
在特定段中设置数据时,将获得该段的锁定。
When getting data, a volatile read is used. If the volatile read results in a miss, then the lock for the segment is obtained for a last attempt at a successful read.
获取数据时,使用易失性读取。如果易失性读取导致未命中,则在最后一次尝试成功读取时获得该段的锁。
回答by Bohemian
Locking is minimized as much as possible while still being thread-safe.
在保持线程安全的同时,尽可能减少锁定。
To explain "part of the Map is locked", this means that when updating, only a "1/concurrencyLevel" of the Map (based on a hash of the key) is locked. This means that two updates can still simultaneously execute safely if they each affect separate "buckets", thus minimizing lock contention and so maximizing performance.
解释“部分地图被锁定”,这意味着在更新时,只有地图的“1/concurrencyLevel”(基于键的散列)被锁定。这意味着如果两个更新都影响单独的“存储桶”,它们仍然可以同时安全地执行,从而最大限度地减少锁争用,从而最大限度地提高性能。
More importantly, trust the JDK implementation - you shouldn't have to worry about implementation details in the JDK (for one thing, it may change from release to release). Rather, just focus on writing yourcode.
更重要的是,信任 JDK 实现——您不必担心 JDK 中的实现细节(一方面,它可能会因发行版而异)。相反,只专注于写你的代码。
回答by Aman Goel
ConcurrentHashMap use Reentrant Lock mechanism. ConcurrentHashMap uses segments instead of buckets and when new record get insert lock will get acquire only on segment not the complete list of segments. So here idea makes its clear that multi level lock will get acquire on the same.
ConcurrentHashMap 使用 Reentrant Lock 机制。ConcurrentHashMap 使用段而不是桶,当新记录获得插入锁时,只会在段上获得,而不是完整的段列表。所以这里的想法清楚地表明,多级锁将在相同的情况下获得。
As no concurrency level has been set explictity, the ConcurrentHashMap gets divided into 16 segments. And each segment acts as an independent HashMap.
由于没有明确设置并发级别,ConcurrentHashMap 被分为 16 个段。每个段充当一个独立的 HashMap。
There is no lock applied on read operation in ConcurrentHashMap.
ConcurrentHashMap 中的读操作没有加锁。