為什么 HashMap 并發(fā)時(shí)會(huì)引起死循環(huán)?
點(diǎn)擊關(guān)注公眾號(hào),Java干貨及時(shí)送達(dá)
今天研讀Java并發(fā)容器和框架時(shí),看到為什么要使用ConcurrentHashMap時(shí),其中有一個(gè)原因是:線程不安全的HashMap, HashMap在并發(fā)執(zhí)行put操作時(shí)會(huì)引起死循環(huán),是因?yàn)槎嗑€程會(huì)導(dǎo)致HashMap的Entry鏈表形成環(huán)形數(shù)據(jù)結(jié)構(gòu),查找時(shí)會(huì)陷入死循環(huán)。
糾起原因看了其他的博客,都比較抽象,所以這里以圖形的方式展示一下,希望支持!
1)當(dāng)往HashMap中添加元素時(shí),會(huì)引起HashMap容器的擴(kuò)容,原理不再解釋?zhuān)苯痈皆创a,如下:
/**
*
* 往表中添加元素,如果插入元素之后,表長(zhǎng)度不夠,便會(huì)調(diào)用resize方法擴(kuò)容
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
/**
* resize()方法如下,重要的是transfer方法,把舊表中的元素添加到新表中
*/
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);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
/**
* 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; ---------------------(1)
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;
} // while
}
}
Map<Integer> map = new HashMap<Integer>(2); // 只能放置兩個(gè)元素,其中的threshold為1(表中只填充一個(gè)元素時(shí)),即插入元素為1時(shí)就擴(kuò)容(由addEntry方法中得知)
//放置2個(gè)元素 3 和 7,若要再放置元素8(經(jīng)hash映射后不等于1)時(shí),會(huì)引起擴(kuò)容

現(xiàn)在有兩個(gè)線程A和B,都要執(zhí)行put操作,即向表中添加元素,即線程A和線程B都會(huì)看到上面圖的狀態(tài)快照。
執(zhí)行順序如下:
執(zhí)行一:線程A執(zhí)行到transfer函數(shù)中(1)處掛起(transfer函數(shù)代碼中有標(biāo)注)。此時(shí)在線程A的棧中:
e = 3
next = 7
執(zhí)行二:線程B執(zhí)行 transfer函數(shù)中的while循環(huán),即會(huì)把原來(lái)的table變成新一table(線程B自己的棧中),再寫(xiě)入到內(nèi)存中。如下圖(假設(shè)兩個(gè)元素在新的hash函數(shù)下也會(huì)映射到同一個(gè)位置)

執(zhí)行三:線程A解掛,接著執(zhí)行(看到的仍是舊表),即從transfer代碼 1)處接著執(zhí)行,當(dāng)前的 e = 3, next = 7, 上面已經(jīng)描述。
1.處理元素 3 , 將 3 放入 線程A自己棧的新table中(新table是處于線程A自己棧中,是線程私有的,不肥線程2的影響),處理3后的圖如下:

2.線程A再?gòu)?fù)制元素 7 ,當(dāng)前 e = 7 ,而next值由于線程 B 修改了它的引用,所以next 為 3 ,處理后的新表如下圖:

3.由于上面取到的next = 3, 接著while循環(huán),即當(dāng)前處理的結(jié)點(diǎn)為3, next就為null ,退出while循環(huán),執(zhí)行完while循環(huán)后,新表中的內(nèi)容如下圖:

4.當(dāng)操作完成,執(zhí)行查找時(shí),會(huì)陷入死循環(huán)!
原文鏈接:https://blog.csdn.net/zhuqiuhui/article/details/51849692
版權(quán)聲明:本文為CSDN博主「bboyzqh」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。






關(guān)注Java技術(shù)??锤喔韶?/strong>


