HashMap源码学习
HashMap實現了Map接口,繼承自AbstractMap,并且是LinkedHashMap的父類。
JDK8中的HashMap
在jdk8中,HashMap的底層的存儲結構是一個Node對象的數組,也叫哈希桶,每個桶放的是鏈表,鏈表中的元素,就是HashMap中的元素。
涉及到擴容,關于擴容的參數有:
- initialCapacity(初始容量),loadFactor(負載因子),threshold(閾值,等于數組的長度乘以loadFactor
JDK8中,當鏈表長度達到8時,會轉化成紅黑樹。
1.鏈表節點Node
與JDK1.7中的HashMap不同,1.8中的鏈表節點類名是Node.
static class Node<K,V> implements Map.Entry<K,V> {final int hash; //哈希值final K key;//keyV value;//valueNode<K,V> next; //后置節點Node(int hash, K key, V value, Node<K,V> next) {this.hash = hash;this.key = key;this.value = value;this.next = next;}public final K getKey() { return key; }public final V getValue() { return value; }public final String toString() { return key + "=" + value; }//每個節點的hashcode是由key的hashcode和value的hashcode進行異或得到的。public final int hashCode() {return Objects.hashCode(key) ^ Objects.hashCode(value);}public final V setValue(V newValue) {V oldValue = value;value = newValue;return oldValue;}public final boolean equals(Object o) {if (o == this)return true;if (o instanceof Map.Entry) {Map.Entry<?,?> e = (Map.Entry<?,?>)o;if (Objects.equals(key, e.getKey()) &&Objects.equals(value, e.getValue()))return true;}return false;}}2.構造方法
在構造方法中,無論傳入的初始容量是多少,HashMap都會通過位運算計算出最接近的2的n次冪的值,從而構造一個2的n次冪的桶
//默認的初始capacity static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 //最大capacity static final int MAXIMUM_CAPACITY = 1 << 30; //默認的load factor static final float DEFAULT_LOAD_FACTOR = 0.75f; //存儲Node節點的數組 transient Node<K,V>[] table; //HashMap中元素數量的閾值,當元素數量超過閾值時,就會發生擴容 int threshold;//負載因子,用于計算HashMap元素數量的閾值,threshold=table.length * loadFactor final float loadFactor; //初始化一個指定初始化capacity和loadfactor的HashMap public HashMap(int initialCapacity, float loadFactor) {//邊界檢查,capacity不能為負數if (initialCapacity < 0)throw new IllegalArgumentException("Illegal initial capacity: " +initialCapacity);
//如果超過最大的capacity,設置為capacityif (initialCapacity > MAXIMUM_CAPACITY)initialCapacity = MAXIMUM_CAPACITY;if (loadFactor <= 0 || Float.isNaN(loadFactor))throw new IllegalArgumentException("Illegal load factor: " +loadFactor);this.loadFactor = loadFactor;
//threshold由initialCapacity計算得來this.threshold = tableSizeFor(initialCapacity); } /*** 根據期望容量cap返回2的n次方的哈希桶的實際容量,返回值一般大于等于cap*/ static final int tableSizeFor(int cap) { //假設cap=3int n = cap - 1;//n=2,二進制寫法是00000010n |= n >>> 1;//先右移一位是00000001,或的結果是00000011n |= n >>> 2;n |= n >>> 4;n |= n >>> 8;n |= n >>> 16;//最終n=3,最后返回n+1return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR); }
public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; } //初始化一個HashMap,將另一個map的元素放入這個HashMap中。 public HashMap(Map<? extends K, ? extends V> m) {this.loadFactor = DEFAULT_LOAD_FACTOR;putMapEntries(m, false); } //將另一個map的所有元素加入表中,參數evict初始化時為false,其他情況為true final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {//先獲取map的大小int s = m.size();//如果大于0if (s > 0) {//如果table此時為nullif (table == null) { // pre-size//根據m的元素數量和負載因子計算出閾值float ft = ((float)s / loadFactor) + 1.0F;//不能超過最大capacityint t = ((ft < (float)MAXIMUM_CAPACITY) ?(int)ft : MAXIMUM_CAPACITY);//如果t大于當前的閾值,返回一個新的滿足2的n次方的閾值if (t > threshold)threshold = tableSizeFor(t);}//如果此時table不為空且m的元素數量大于thresholdelse if (s > threshold)resize();//擴容,以便容納m的所有元素,有可能出現擴容以后還是無法容納所有元素,但因為putVal方法里面會擴容。//遍歷m依次將元素放入HashMap中for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {K key = e.getKey();V value = e.getValue();putVal(hash(key), key, value, false, evict);}} }
3.hash()方法
static final int hash(Object key) {int h;return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}h>>>16剛好是獲取了高位部分,最后是hashcode的低位和高位做異或,增加低位的隨機性。
3.擴容函數
擴容函數用于初始化或者擴大哈希桶的大小為原來的兩倍,返回擴容后的Node數組。
? ?如果當前哈希桶為空,分配符合當前閾值的初始容量目標,如果不為空就擴容為原來的兩倍。
? ?
final Node<K,V>[] resize() {//oldTab為當前哈希桶Node<K,V>[] oldTab = table;//oldCap為當前哈希桶的容量int oldCap = (oldTab == null) ? 0 : oldTab.length;//oldThr為當前的閾值int oldThr = threshold;//初始化newCap和newThr為0int newCap, newThr = 0;//如果當前哈希桶容量大于0if (oldCap > 0) {//如果當前哈希桶容量大于等于最大容量,就只好隨你碰撞了if (oldCap >= MAXIMUM_CAPACITY) {//閾值為int類型的最大值threshold = Integer.MAX_VALUE;//返回當前哈希桶,不再擴容return oldTab;}//newCap等于當前哈希桶容量的兩倍,如果這個值小于最大容量,且當前哈希桶容量大于等于默認初始容量else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&oldCap >= DEFAULT_INITIAL_CAPACITY)//則新的閾值等于當前閾值的兩倍newThr = oldThr << 1; // double threshold}//如果當前哈希桶為空,但是有閾值,代表是初始化時指定了容量閾值的情況else if (oldThr > 0) // initial capacity was placed in thresholdnewCap = oldThr;//則新的容量等于當前閾值else { // 如果當前哈希桶為空,且閾值也為0newCap = DEFAULT_INITIAL_CAPACITY;//新的容量為默認初始容量//新的閾值等于默認負載因子乘以默認初始容量newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);}if (newThr == 0) {//如果新的閾值時0,即當前表是空的,但是有閾值,此時newCap等于當前閾值float ft = (float)newCap * loadFactor;//根據新表容量和負載因子求出新的閾值,這樣的話新表的容量就大于新的閾值了newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?(int)ft : Integer.MAX_VALUE);}//更新閾值threshold = newThr;@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//更新tabletable = newTab;if (oldTab != null) {//當當前的table數組不為空時,重新分配數組中的數據。for (int j = 0; j < oldCap; ++j) {Node<K,V> e;if ((e = oldTab[j]) != null) {//將原鏈表置空,以便GColdTab[j] = null;//如果當前節點沒有后續節點,直接賦值if (e.next == null)newTab[e.hash & (newCap - 1)] = e;else if (e instanceof TreeNode)((TreeNode<K,V>)e).split(this, newTab, j, oldCap);else { // 如果當前節點有后續節點,則要進行重新分配Node<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;//留在原位置的節點if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}//移動到原位置+oldCap的節點else {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);if (loTail != null) {loTail.next = null;newTab[j] = loHead;}if (hiTail != null) {hiTail.next = null;newTab[j + oldCap] = hiHead;}}}}}return newTab;}?擴容后,由于哈希桶的長度變化,集合中的部分元素的位置也會發生變化。JDK8中采用了一個非常巧妙的計算方式,來判斷哪些元素需要變動位置,哪些元素不需要。
下圖表示擴容前key1和key2的hash值,以及key1和key2在哈希桶中的位置(為了方便畫圖只顯示8個位,實際上有32個位),此時key1和key2在哈希桶的位置((n-1)&key)是相同的。
下圖是擴容后key1和key2的hash值,此時可以發現,key1的位置并沒有變動,而key2的位置發生了變動。
key2的原位置由5變為21,中間增加了16,而16恰好是原有的哈希桶大小00010000(在resize函數里就是局部變量oldCap)。
由此發現,位置是否移動,取決于key和新增的一位是1還是0,當key&oldCap等于0(也就是新增的一位為0,如00000101)時,位置不需要移動,當key&oldCap不等于0(新增的一位為1,如00010101),key在哈希桶中的索引為原位置+oldCap。
JDK8這樣優化的好處是,省去了重新計算hash值的時間,由于新增的一位是0還是1是隨機的,所以這樣一來,就將原有沖突的元素均勻地分到新的位置了。
4.Put函數
//put方法實際上調用了putVal方法 public V put(K key, V value) {return putVal(hash(key), key, value, false, true); }final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {Node<K,V>[] tab; Node<K,V> p; int n, i;//如果table數組為空,則首先擴容,n為擴容后的長度if ((tab = table) == null || (n = tab.length) == 0)n = (tab = resize()).length;//(n-1)&hash計算當前的key在數組中的位置,如果該位置上還沒有結點,直接putif ((p = tab[i = (n - 1) & hash]) == null)tab[i] = newNode(hash, key, value, null);//如果已經有結點了else {Node<K,V> e; K k;//如果結點的key值與要插入的key值相同,直接覆蓋if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))e = p;//如果是紅黑樹else if (p instanceof TreeNode)e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//否則就要遍歷結點所在鏈表后,添加在鏈表的尾部,e此時為頭結點else {for (int binCount = 0; ; ++binCount) {//當找到鏈表的尾部時即下一個節點為空,在鏈表的尾部添加新的結點if ((e = p.next) == null) {p.next = newNode(hash, key, value, null);//當鏈表的長度超過8,就調用treeifyBin函數
//當tab的大小超過64,就將鏈表轉化為一棵紅黑樹,否則調用resize進行擴容
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}//如果在遍歷鏈表的時候發現有結點的key值與要插入的key值相同,退出循環if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))break;p = e;}}//當e不為null時,此時說明鏈表中存在要插入的keyif (e != null) { // existing mapping for keyV oldValue = e.value;//當onlyIfAbsent為false,即在存在相同的key值時進行替換(如果為true則不替換)if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);//返回原有的值return oldValue;}}//modCount加1++modCount;if (++size > threshold) //檢查是否超過閾值resize();afterNodeInsertion(evict);return null; //因為原hashMap中key不存在,所有返回null}
5.Get函數
public V get(Object key) {Node<K,V> e;return (e = getNode(hash(key), key)) == null ? null : e.value;}/*** Implements Map.get and related methods** @param hash hash for key* @param key the key* @return the node, or null if none*/final Node<K,V> getNode(int hash, Object key) {Node<K,V>[] tab; Node<K,V> first, e; int n; K k;//如果table數組不為空,并且對應位置的鏈表頭結點不為空if ((tab = table) != null && (n = tab.length) > 0 &&(first = tab[(n - 1) & hash]) != null) {//如果key與鏈表頭結點相同,則返回鏈表頭結點if (first.hash == hash && // always check first node((k = first.key) == key || (key != null && key.equals(k))))return first;//如果key與鏈表頭結點不同,則遍歷鏈表if ((e = first.next) != null) {if (first instanceof TreeNode)return ((TreeNode<K,V>)first).getTreeNode(hash, key);do {if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))return e;} while ((e = e.next) != null);}}return null;}6.Remove方法
/*** Removes the mapping for the specified key from this map if present.** @param key key whose mapping is to be removed from the map* @return the previous value associated with <tt>key</tt>, or* <tt>null</tt> if there was no mapping for <tt>key</tt>.* (A <tt>null</tt> return can also indicate that the map* previously associated <tt>null</tt> with <tt>key</tt>.)*/public V remove(Object key) {Node<K,V> e;return (e = removeNode(hash(key), key, null, false, true)) == null ?null : e.value;}/*** Implements Map.remove and related methods** @param hash hash for key* @param key the key* @param value the value to match if matchValue, else ignored* @param matchValue if true only remove if value is equal* @param movable if false do not move other nodes while removing* @return the node, or null if none*/final Node<K,V> removeNode(int hash, Object key, Object value,boolean matchValue, boolean movable) {Node<K,V>[] tab; Node<K,V> p; int n, index;//如果table數組不為空,并且對應位置鏈表的頭結點不為空if ((tab = table) != null && (n = tab.length) > 0 &&(p = tab[index = (n - 1) & hash]) != null) {Node<K,V> node = null, e; K k; V v;
//如果要刪除的key與鏈表頭結點的key相同,則說明要刪除的結點就是鏈表頭結點if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))node = p;
//遍歷以找到要刪除的結點,以及要刪除結點的上一個結點pelse if ((e = p.next) != null) {if (p instanceof TreeNode)node = ((TreeNode<K,V>)p).getTreeNode(hash, key);else {do {if (e.hash == hash &&((k = e.key) == key ||(key != null && key.equals(k)))) {node = e;break;}p = e;} while ((e = e.next) != null);}}if (node != null && (!matchValue || (v = node.value) == value ||(value != null && value.equals(v)))) {if (node instanceof TreeNode)((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);else if (node == p)//如果要刪除的結點是鏈表的頭結點tab[index] = node.next;//將table數組對應位置賦值給其下一個結點elsep.next = node.next;++modCount;--size;afterNodeRemoval(node);return node;}}return null;}
JDK7中的HashMap
一.鏈表節點Entry
jdk 1.7中用Entry作為鏈表節點類。
static class Entry<K,V> implements Map.Entry<K,V> {final K key;V value;Entry<K,V> next;int hash;/*** Creates new entry.*/Entry(int h, K k, V v, Entry<K,V> n) {value = v;next = n;key = k;hash = h;}public final K getKey() {return key;}public final V getValue() {return value;}public final V setValue(V newValue) {V oldValue = value;value = newValue;return oldValue;}public final boolean equals(Object o) {if (!(o instanceof Map.Entry))return false;Map.Entry e = (Map.Entry)o;Object k1 = getKey();Object k2 = e.getKey();if (k1 == k2 || (k1 != null && k1.equals(k2))) {Object v1 = getValue();Object v2 = e.getValue();if (v1 == v2 || (v1 != null && v1.equals(v2)))return true;}return false;}public final int hashCode() {return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());}public final String toString() {return getKey() + "=" + getValue();}/*** This method is invoked whenever the value in an entry is* overwritten by an invocation of put(k,v) for a key k that's already* in the HashMap.*/void recordAccess(HashMap<K,V> m) {}/*** This method is invoked whenever the entry is* removed from the table.*/void recordRemoval(HashMap<K,V> m) {}}Entry是HashMap的內部類, 從成員變量可以看出
- key是HashMap中的key
- value是HashMap中的value
- next指向下一個鏈表節點
- hash表示hash值
二.Put方法
public V put(K key, V value) {if (table == EMPTY_TABLE) {inflateTable(threshold);}if (key == null)return putForNullKey(value);int hash = hash(key);int i = indexFor(hash, table.length);for (Entry<K,V> e = table[i]; e != null; e = e.next) {Object k;if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {V oldValue = e.value;e.value = value;e.recordAccess(this);return oldValue;}}modCount++;addEntry(hash, key, value, i);return null;}第一步,判斷數組是否為空,是否需要初始化
第二步,如果key為null,則put一個空值進去
第三步,計算key的哈希值
第四步,根據哈希值定位到對應的桶,即在數組中的位置
第五步,遍歷桶中的鏈表,看是否找到hashcode相等的、key相等的節點,如果有則覆蓋原來的值,返回原來的值
第六步,如果找不到hashcode相等和key相等的節點,就將其添加到桶對應的鏈表的頭部(從addEntry方法可以看出)
1)hash方法和indexFor方法
indexFor方法輸入key的hash值和桶的大小,返回桶的位置。
/*** Returns index for hash code h.*/static int indexFor(int h, int length) {// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";return h & (length-1);}indexFor方法返回桶的位置,因為length總是等于2的n次方,所以h&(length-1)時相當于對length取模(即h%length)。
因為HashMap中桶的大小為2的n次冪,所以與運算的結果是高位全部歸零,低位作為index.例如此時桶大小為16,16-1=15,二進制表示0000000000000000000001111
1010010111000100001000101 & 0000000000000000000001111 ---------------------------------------0000000000000000000000101得到的結果是截取了最后四位,如果只通過最后四位來決定散列的結果,容易導致碰撞,所以需要用hash函數來進行“擾動”。
所以HashMap中元素的哈希值不僅僅是key的hashcode而已,而是經過了一些位運算,增加低位的隨機性,從而減少碰撞。
/*** Retrieve object hash code and applies a supplemental hash function to the* result hash, which defends against poor quality hash functions. This is* critical because HashMap uses power-of-two length hash tables, that* otherwise encounter collisions for hashCodes that do not differ* in lower bits. Note: Null keys always map to hash 0, thus index 0.*/final int hash(Object k) {int h = hashSeed;if (0 != h && k instanceof String) {return sun.misc.Hashing.stringHash32((String) k);}h ^= k.hashCode();// This function ensures that hashCodes that differ only by// constant multiples at each bit position have a bounded// number of collisions (approximately 8 at default load factor).h ^= (h >>> 20) ^ (h >>> 12);return h ^ (h >>> 7) ^ (h >>> 4);}?
2)addEntry和createEntry方法
/*** Adds a new entry with the specified key, value and hash code to* the specified bucket. It is the responsibility of this* method to resize the table if appropriate.** Subclass overrides this to alter the behavior of put method.*/void addEntry(int hash, K key, V value, int bucketIndex) {if ((size >= threshold) && (null != table[bucketIndex])) {resize(2 * table.length);hash = (null != key) ? hash(key) : 0;bucketIndex = indexFor(hash, table.length);}createEntry(hash, key, value, bucketIndex);}void createEntry(int hash, K key, V value, int bucketIndex) {//獲取了桶中鏈表的頭結點Entry<K,V> e = table[bucketIndex];table[bucketIndex] = new Entry<>(hash, key, value, e);size++;}
HashMap通過調用addEntry方法來添加一個Entry對象,hash表示hashcode,key/value不用說,bucketIndex是桶的位置即數組的索引。
1.如果容器大小超過了閾值并且桶不為空,則要擴容成原來的兩倍,并且將當前的key重新hash重新定位得到新的bucketIndex'
? ? 2.最終都調用了createEntry方法,createEntry首先獲取了桶中鏈表的頭結點(有可能是null)
? ? 3.創建了一個新的Entry對象,并將Entry中的next指向原來的頭結點,也就是說新的Entry成為了桶中鏈表的新的頭結點。
三.擴容函數resize方法
void resize(int newCapacity) {Entry[] oldTable = table;int oldCapacity = oldTable.length;if (oldCapacity == MAXIMUM_CAPACITY) {threshold = Integer.MAX_VALUE;return;}Entry[] newTable = new Entry[newCapacity];transfer(newTable, initHashSeedAsNeeded(newCapacity));table = newTable;threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);}/*** Transfers all entries from current table to newTable.*/void transfer(Entry[] newTable, boolean rehash) {int newCapacity = newTable.length;for (Entry<K,V> e : table) {while(null != e) {Entry<K,V> next = e.next;if (rehash) {e.hash = null == e.key ? 0 : hash(e.key);}int i = indexFor(e.hash, newCapacity);e.next = newTable[i];newTable[i] = e;e = next;}}}1.首先判斷現在的容量是否等于最大容量,如果大于那么閾值就等于int中的最大值(意味著已經達到最大容量了,不能再擴容了)
2.如果現在的容量小于最大容量,那么就創建一個新的Entry數組,將舊的Entry對象轉移到新的Entry數組中。
3.將閾值更新為新的容量乘以負載因子和最大容量中的較小值。
四.get方法
public V get(Object key) {if (key == null)return getForNullKey();Entry<K,V> entry = getEntry(key);return null == entry ? null : entry.getValue();}/*** Returns the entry associated with the specified key in the* HashMap. Returns null if the HashMap contains no mapping* for the key.*/final Entry<K,V> getEntry(Object key) {if (size == 0) {return null;}int hash = (key == null) ? 0 : hash(key);for (Entry<K,V> e = table[indexFor(hash, table.length)];e != null;e = e.next) {Object k;if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))return e;}return null;}1.如果key為null,就獲取key值為null的value
2.如果key非空,如果桶的大小為0,返回null.否則計算key的hash值,定位所在桶的位置
3.遍歷桶中的元素,當有hashcode相同,key相同時,則返回對應的值,如果找不到則返回null
三、jdk8的HashMap的優化
1.在jdk7的HashMap中,當Hash沖突嚴重時,桶上的鏈表就會越來越長,從而導致查詢效率降為O(N)
? jdk8的HashMap在桶上的鏈表達到8時,會將鏈表轉化為紅黑樹。
2.jdk7中,數組擴容后,通過key的hashcode對數組長度進行取模的方式來調整數組中的元素
jdk8中,數組擴容后,通過key的hashcode與原來的size進行與運算(因為擴容后是原來size的兩倍),若等于0,則不需要移動,否則就移動原來的索引加上size的大小。
由于與運算的結果可以說是隨機的,所以jdk8的解決辦法使得元素分布得更加均勻,并且不會倒置。
四、HashMap中的線程安全問題
為什么在多線程的情況下,向HashMap放入元素會導致死循環呢?
主要是在擴容后轉移鏈表節點時導致形成了環形鏈表
以jdk7中的resize為例
void resize(int newCapacity) {Entry[] oldTable = table;int oldCapacity = oldTable.length;if (oldCapacity == MAXIMUM_CAPACITY) {threshold = Integer.MAX_VALUE;return;}Entry[] newTable = new Entry[newCapacity];transfer(newTable, initHashSeedAsNeeded(newCapacity));table = newTable;threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);}/*** Transfers all entries from current table to newTable.*/void transfer(Entry[] newTable, boolean rehash) {int newCapacity = newTable.length;for (Entry<K,V> e : table) {while(null != e) {Entry<K,V> next = e.next;if (rehash) {e.hash = null == e.key ? 0 : hash(e.key);}int i = indexFor(e.hash, newCapacity);e.next = newTable[i];newTable[i] = e;e = next;}}}?例如以下這個場景,線程一執行到Entry<K,V> next=e.next這一句時,e指向KEY=3的節點,next指向KEY=7的節點
此時CPU時間片輪轉,執行權交給了線程二,線程二執行了所有的代碼。
?
執行權又回到了線程一,線程一調用indexFor方法獲取到KEY=3的最新位置,并將KEY=3的next指向了KEY=7。
此時KEY=3和KEY=7形成了環形鏈表,e就一直不等于NULL,所以一直無法跳出循環。
?參考鏈接
https://tech.meituan.com/java_hashmap.html
https://crossoverjie.top/2018/07/23/java-senior/ConcurrentHashMap/
https://www.zhihu.com/question/20733617 HashMap中的hash方法解析
https://www.cnblogs.com/dongguacai/p/5599100.html HashMap中的線程安全問題
?
轉載于:https://www.cnblogs.com/qingfei1994/p/9151915.html
總結
以上是生活随笔為你收集整理的HashMap源码学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3 函数笔记
- 下一篇: 队列 一种数据结构(多线程利器)