圖解HashMap爲什麼線程不安全?

HashMap的線程不安全主要體現在下面兩個方面:
1.在JDK1.7中,當併發執行擴容操作時會造成環形鏈和數據丟失的情況。
2.在JDK1.8中,在併發執行put操作時會發生數據覆蓋的情況。

JDK1.7

在JDK1.7中,擴容數據時要進行把原數據遷移到新的位置,使用的方法:

//數據遷移的方法,頭插法添加元素
void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
     //for循環中的代碼,逐個遍歷鏈表,重新計算索引位置,將老數組數據複製到新數組中去(數組不存儲實際數據,所以僅僅是拷貝引用而已)
        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);
                //將當前entry的next鏈指向新的索引位置,newTable[i]有可能爲空,有可能也是個entry鏈,如果是entry鏈,直接在鏈表頭部插入。
                //以下三行是線程不安全的關鍵
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

這段代碼是HashMap在JDK1.7的擴容操作,重新定位每個桶的下標,並採用頭插法將元素遷移到新數組中。頭插法會將鏈表的順序翻轉,這也是形成死循環的關鍵點。

將關鍵的幾行代碼提取出:

for (Entry<K,V> e : table) {
	while(null != e) {
	   Entry<K,V> next = e.next;
	   e.next = newTable[i];
	   newTable[i] = e;
	   e = next;
	}
}

假設有兩個線程,每個線程都有一個e指針和next指針,線程1的爲e1和next1,線程2的爲e2,next2。

假設線程1執行到 Entry<K,V> next = e.next 後,線程被掛起,此時e1指向10,next1 指向 6。
在這裏插入圖片描述

接着線程2開始執行,和線程1一樣,先執行 Entry<K,V> next = e.next;將e2執向10,將next2指向6:
在這裏插入圖片描述
然後執行e.next = newTable[i]; 因爲newTable[i]此時爲null,所以e2.nextnull,也就是讓10指向空。
執行newTable[i] = e;將10複製到newTable[i]當中:
在這裏插入圖片描述
執行e = next;執行前e2指向的是10,next2執向的是6,執行後e2指向了6。
在這裏插入圖片描述
執行到此線程2的第一輪循環結束,開始第二輪執行:

for (Entry<K,V> e : table) {
	while(null != e) {
	   Entry<K,V> next = e.next;
	   e.next = newTable[i];
	   newTable[i] = e;
	   e = next;
	}
}

執行Entry<K,V> next = e.next; e就是e2嘍,此時指向的是6,那麼e.next就是null,意思就是讓next2爲null:
在這裏插入圖片描述
然後執行e.next = newTable[i]; 因爲Table[i]此時已經有了值爲10e2指向6,所以執行後e2.next指向了新表中的10
在這裏插入圖片描述
執行newTable[i] = e;將6複製到newTable[i]當中,假如6在新表中的位置和10一樣的話,執行這一步的結果就是:
在這裏插入圖片描述
執行e = next;將e2指向null。執行前next2是爲空的,執行後e2也就爲空:
在這裏插入圖片描述
線程2執行完畢。線程1繼續執行,之前是執行到了:Entry<K,V> next = e.next; 此時e1執向的還是10,next1指向的是6,。

for (Entry<K,V> e : table) {
	while(null != e) {
	   Entry<K,V> next = e.next;
	   e.next = newTable[i];
	   newTable[i] = e;
	   e = next;
	}
}

接下來線程1執行e.next = newTable[i]; 線程1的newTable[i]此時爲空:
在這裏插入圖片描述
執行newTable[i] = e; 就是將10這個節點放入到新數組:
在這裏插入圖片描述
執行e = next; 執行前next1指向的是6,e1執行的是10,執行後,e1指向了6:

在這裏插入圖片描述
線程1第一輪循環執行結束,開始執行第二輪循環:

	   Entry<K,V> next = e.next;
	   e.next = newTable[i];
	   newTable[i] = e;
	   e = next;

執行Entry<K,V> next = e.next; 執行前e1指向的是6,e1.next指向的是10,next1指向的也是6,此時就是讓next1指向10:

在這裏插入圖片描述
繼續執行e.next = newTable[i]; 此時newTable[i]已經是10,e1是6,e.next本來就是指向10,執行前後結果並沒有發生變化。

執行newTable[i] = e; e1指向的是6,把6複製到新的數組當中:

在這裏插入圖片描述
執行e = next;``next1執行前指向的是10,將e1指向10:
在這裏插入圖片描述
第二輪循環執行結束,開始第三輪循環。
執行Entry<K,V> next = e.next;,e1原本指向的10,e1.next就是null,執行後next1指向null:
在這裏插入圖片描述
執行e.next = newTable[i]; newTable[i]本來是6,e1執行的是10,e1.next本來是null,執行結束後就是讓10指向了6:
在這裏插入圖片描述
此時環路形成了,陷入了死循環

JDK1.8

對於JDK1.8當中,添加元素使用尾插法。如果對應角標是單向鏈表,將單向鏈表進行遷移,如果是紅黑樹,將雙向鏈表進行數據遷移。
看一下下面這段JDK1.8中的put操作代碼:

 1 public V put(K key, V value) {
 2     // 對key的hashCode()做hash
 3     return putVal(hash(key), key, value, false, true);
 4 }
 5 
 6 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
 7                boolean evict) {
 8     Node<K,V>[] tab; Node<K,V> p; int n, i;
 9     // 步驟①:table爲空則創建,觸發resize方法
10     if ((tab = table) == null || (n = tab.length) == 0)
11         n = (tab = resize()).length;
12     // 步驟②:計算index,並對null做處理 
13     if ((p = tab[i = (n - 1) & hash]) == null) 
14         tab[i] = newNode(hash, key, value, null);
15     else {
16         Node<K,V> e; K k;
17         // 步驟③:節點key存在,直接覆蓋value
18         if (p.hash == hash &&
19             ((k = p.key) == key || (key != null && key.equals(k))))
20             e = p;
21         // 步驟④:判斷該鏈爲紅黑樹
22         else if (p instanceof TreeNode)
23             e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
24         // 步驟⑤:該鏈爲鏈表
25         else {
26             for (int binCount = 0; ; ++binCount) {
27                 if ((e = p.next) == null) {
						//對於計算出的存儲位置下標已經有數據,也就是衝突,轉成鏈表存到下一位
28                     p.next = newNode(hash, key,value,null);  
                        //鏈表長度大於8轉換爲紅黑樹進行處理
29                     if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st  
30                         treeifyBin(tab, hash);
31                     break;
32                 }
                    // key已經存在直接覆蓋value
33                 if (e.hash == hash &&
34                     ((k = e.key) == key || (key != null && key.equals(k)))) 
35                            break;
36                 p = e;
37             }
38         }
39         
40         if (e != null) { // existing mapping for key
41             V oldValue = e.value;
42             if (!onlyIfAbsent || oldValue == null)
43                 e.value = value;
44             afterNodeAccess(e);
45             return oldValue;
46         }
47     }
 
48     ++modCount;
49     // 步驟⑥:超過最大容量就擴容,門限原本是初始容量*0.75
50     if (++size > threshold)
51         resize(); //擴原來的2倍
52     afterNodeInsertion(evict);
53     return null;
54 }

其中第13行代碼是判斷是否出現hash碰撞,假設兩個線程A、B都在進行put操作,並且hash函數計算出的插入下標是相同的,當線程A執行完第13行代碼後由於時間片耗盡導致被掛起,而線程B得到時間片後在該下標處插入了元素,完成了正常的插入,然後線程A獲得時間片,由於之前已經進行了hash碰撞的判斷,所有此時不會再進行判斷,而是直接進行插入,這就導致了線程B插入的數據被線程A覆蓋了,從而線程不安全。
除此之前,還有就是代碼的第50行處有個++size,我們這樣想,還是線程A、B,這兩個線程同時進行put操作時,假設當前HashMap的zise大小爲10,當線程A執行到第50行代碼時,從主內存中獲得size的值爲10後準備進行+1操作,但是由於時間片耗盡只好讓出CPU,線程B快樂的拿到CPU還是從主內存中拿到size的值10進行+1操作,完成了put操作並將size=11寫回主內存,然後線程A再次拿到CPU並繼續執行(此時size的值仍爲10),當執行完put操作後,還是將size=11寫回內存,此時,線程A、B都執行了一次put操作,但是size的值只增加了1,所有說還是由於數據覆蓋又導致了線程不安全。

Jdk1.8當中如何解決HashMap擴容成環問題

擴容源碼:

    final Node< K,V >[] resize() {
            Node< K,V >[] oldTab = table;
            int oldCap = (oldTab == null) ? 0 : oldTab.length;
            int oldThr = threshold;
            int newCap, newThr = 0;
            if (oldCap > 0) {
                if (oldCap >= MAXIMUM_CAPACITY) {
                    threshold = Integer.MAX_VALUE;
                    return oldTab;
                }
                //在容量不超過做大容量的時候,擴容擴大爲原來的兩倍
                else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                         oldCap >= DEFAULT_INITIAL_CAPACITY)
                    newThr = oldThr << 1; // double threshold
            }

           ...省略部分代碼
            @SuppressWarnings({"rawtypes","unchecked"})
                Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
            table = newTab;
            //遍歷舊數組中的元素,複製到table數組中
            if (oldTab != null) {
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
//在這裏可能會出現數據丟失
                    if ((e = oldTab[j]) != null) {
                        oldTab[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 { // preserve order
                            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;
                                    else
                                        loTail.next = e;
                                    loTail = e;
                                }
                                else {
                                    if (hiTail == null)
                                        hiHead = e;
                                    else
                                        hiTail.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;
        }
.

在JDK1.8中機智的使用兩組指針解決這個問題,主要代碼如下:

 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;
         else
             loTail.next = e;
         loTail = e;
     }
     else {
         if (hiTail == null)
             hiHead = e;
         else
             hiTail.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;
 }

定義了兩組指針,分別是高位指針和低位指針:

 Node< K,V > loHead = null, loTail = null;
 Node< K,V > hiHead = null, hiTail = null;

這兩組指針將鏈表分成了兩部分,高位指針指向哪些擴容後下標變爲(舊索引+擴容大小),低位指針指向哪些擴容後下標還保持不變的節點。分成兩條鏈表今次那個遷移,遷移後節點的前後順序保持不變,不會出現環的情況。

另外可以看到我們在擴充HashMap的時候,不需要像JDK1.7的實現那樣重新計算hash,只需要看看原來的hash值新增的那個bit是1還是0就好了,是0的話索引沒變,是1的話索引變成“原索引+oldCap”

擴容的地方是紅黑樹

上面看到的擴容的地方是鏈表,如果是紅黑樹呢?

//這個函數的功能是對紅黑樹進行 rehash 操作
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
        TreeNode<K,V> b = this;
        // Relink into lo and hi lists, preserving order
        TreeNode<K,V> loHead = null, loTail = null;
        TreeNode<K,V> hiHead = null, hiTail = null;
        int lc = 0, hc = 0;
     //由於 TreeNode 節點之間存在雙端鏈表的關係,可以利用鏈表關係進行 rehash
        for (TreeNode<K,V> e = b, next; e != null; e = next) {
            next = (TreeNode<K,V>)e.next;
            e.next = null;
            if ((e.hash & bit) == 0) {
                if ((e.prev = loTail) == null)
                    loHead = e;
                else
                    loTail.next = e;
                loTail = e;
                ++lc;
            }
            else {
                if ((e.prev = hiTail) == null)
                    hiHead = e;
                else
                    hiTail.next = e;
                hiTail = e;
                ++hc;
            }
        }
         
        //rehash 操作之後注意對根據鏈表長度進行 untreeify 或 treeify 操作
        if (loHead != null) {
            if (lc <= UNTREEIFY_THRESHOLD)
                tab[index] = loHead.untreeify(map);
            else {
                tab[index] = loHead;
                if (hiHead != null) // (else is already treeified)
                    loHead.treeify(tab);
            }
        }
        if (hiHead != null) {
            if (hc <= UNTREEIFY_THRESHOLD)
                tab[index + bit] = hiHead.untreeify(map);
            else {
                tab[index + bit] = hiHead;
                if (loHead != null)
                    hiHead.treeify(tab);
            }
        }//end if
    }//end split

可以看到由TreeNode 節點之間存在雙端鏈表的關係,可以利用鏈表關係進行處理紅黑樹,也就是說紅黑樹裏還存着next的信息,只不過平時不用,到擴容的時候就用上了,作爲鏈表來處理,分爲高位鏈表和低位鏈表。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章