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