问题描述
我了解在HashMap中,条目(Key,Value)是根据hash(Key.hashCode)放在桶中的-->表示桶位置的索引.如果条目已经放置在该位置,则会创建一个链表,并且新条目(如果它具有不同的键 --> 通过 equals() 方法)放置在链表的开头.
I understand that in HashMap, the entries (Key, Value) are placed in buckets based on hash(Key.hashCode)--> The index that denotes the bucket location. In case an entry is already placed at that location, there is a linked list created and the new entry (if it has different key --> via equals() method) is placed at the beginning of the linked list.
- 我能否将这个概念与 ConcurrentHashMap 的概念相关联,但不是 Buckets,而是有各个线程在其上具有锁的 Segment.而不是 Entries,有 HashEntry(ies).以类似的方式创建一个链表,如果插入的键值对不同,则根据键的 equals() 将其放在链表的末尾.
- 我这样说对吗:CHM 的 put 是不同步的,因此任何线程都可以访问这个方法,这个 put 方法计算传递给它的键的哈希值并获取段索引(有点像桶).然后仅针对该段,它调用 put 方法.现在在 Segment 下, put 方法指定将有一个 lock(),因此只有一个线程可以更改特定段中的数据,因此得出结论,如果并发级别为 16,则应有 16 个线程,因此这些线程将是一次只能PUT值一个段.
推荐答案
桶是地图数组中的一个单独的槽.这对于
HashMap
和ConcurrentHashMap
都是一样的.从概念上讲,后者将其数组分解为段(每个段都是引用数组),仅此而已.请注意,Java 8 中的 CHM 不再有段,而是一个数组.
A bucket is an individual slot in the map's array. This is the same with both
HashMap
andConcurrentHashMap
. Conceptually, the latter has its array broken into segments (each segment is an array of references), but that's it. Note that the CHM in Java 8 no longer has segments, it's all a single array.
是的,这就是称为分段锁定的方案.它减少了线程间争用,但并没有消除它.
Yes, it's the scheme known as segmented locking. It reduces inter-thread contention, but does not eliminate it.
这篇关于ConcurrentHashMap的Segment和HashMap的bucket在理论上有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!