問(wèn)題描述
我了解在HashMap中,條目(Key,Value)是根據(jù)hash(Key.hashCode)放在桶中的-->表示桶位置的索引.如果條目已經(jīng)放置在該位置,則會(huì)創(chuàng)建一個(gè)鏈表,并且新條目(如果它具有不同的鍵 --> 通過(guò) equals() 方法)放置在鏈表的開(kāi)頭.
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.
- 我能否將這個(gè)概念與 ConcurrentHashMap 的概念相關(guān)聯(lián),但不是 Buckets,而是有各個(gè)線程在其上具有鎖的 Segment.而不是 Entries,有 HashEntry(ies).以類似的方式創(chuàng)建一個(gè)鏈表,如果插入的鍵值對(duì)不同,則根據(jù)鍵的 equals() 將其放在鏈表的末尾.
- 我這樣說(shuō)對(duì)嗎:CHM 的 put 是不同步的,因此任何線程都可以訪問(wèn)這個(gè)方法,這個(gè) put 方法計(jì)算傳遞給它的鍵的哈希值并獲取段索引(有點(diǎn)像桶).然后僅針對(duì)該段,它調(diào)用 put 方法.現(xiàn)在在 Segment 下, put 方法指定將有一個(gè) lock(),因此只有一個(gè)線程可以更改特定段中的數(shù)據(jù),因此得出結(jié)論,如果并發(fā)級(jí)別為 16,則應(yīng)有 16 個(gè)線程,因此這些線程將是一次只能PUT值一個(gè)段.
推薦答案
桶是地圖數(shù)組中的一個(gè)單獨(dú)的槽.這對(duì)于
HashMap
和ConcurrentHashMap
都是一樣的.從概念上講,后者將其數(shù)組分解為段(每個(gè)段都是引用數(shù)組),僅此而已.請(qǐng)注意,Java 8 中的 CHM 不再有段,而是一個(gè)數(shù)組.
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.
是的,這就是稱為分段鎖定的方案.它減少了線程間爭(zhēng)用,但并沒(méi)有消除它.
Yes, it's the scheme known as segmented locking. It reduces inter-thread contention, but does not eliminate it.
這篇關(guān)于ConcurrentHashMap的Segment和HashMap的bucket在理論上有什么區(qū)別?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!