轉載自 https://blog.csdn.net/zhuqiuhui/article/details/51849692
今天研讀Java並發容器和框架時,看到為什么要使用ConcurrentHashMap時,其中有一個原因是:線程不安全的HashMap, HashMap在並發執行put操作時會引起死循環,是因為多線程會導致HashMap的Entry鏈表形成環形數據結構,查找時會陷入死循環。糾起原因看了其他的博客,都比較抽象,所以這里以圖形的方式展示一下,希望支持!
(1)當往HashMap中添加元素時,會引起HashMap容器的擴容,原理不再解釋,直接附源代碼,如下:
-
/**
-
*
-
* 往表中添加元素,如果插入元素之后,表長度不夠,便會調用resize方法擴容
-
*/
-
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);
-
}
(2)參考上面的代碼,便引入到了transfer方法,(引入重點)這就是HashMap並發時,會引起死循環的根本原因所在,下面結合transfer的源代碼,說明一下產生死循環的原理,先列transfer代碼(這是里JDK7的源偌),如下:
-
/**
-
* 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
-
-
}
-
}
(3)假設:
-
Map<Integer> map =
new HashMap<Integer>(
2);
// 只能放置兩個元素,其中的threshold為1(表中只填充一個元素時),即插入元素為1時就擴容(由addEntry方法中得知)
-
//放置2個元素 3 和 7,若要再放置元素8(經hash映射后不等於1)時,會引起擴容
假設放置結果圖如下:
現在有兩個線程A和B,都要執行put操作,即向表中添加元素,即線程A和線程B都會看到上面圖的狀態快照
執行順序如下:
執行一: 線程A執行到transfer函數中(1)處掛起(transfer函數代碼中有標注)。此時在線程A的棧中
-
e =
3
-
next =
7
執行二:線程B執行 transfer函數中的while循環,即會把原來的table變成新一table(線程B自己的棧中),再寫入到內存中。如下圖(假設兩個元素在新的hash函數下也會映射到同一個位置)
執行三: 線程A解掛,接着執行(看到的仍是舊表),即從transfer代碼(1)處接着執行,當前的 e = 3, next = 7, 上面已經描述。
1. 處理元素 3 , 將 3 放入 線程A自己棧的新table中(新table是處於線程A自己棧中,是線程私有的,不肥線程2的影響),處理3后的圖如下:
2. 線程A再復制元素 7 ,當前 e = 7 ,而next值由於線程 B 修改了它的引用,所以next 為 3 ,處理后的新表如下圖
3. 由於上面取到的next = 3, 接着while循環,即當前處理的結點為3, next就為null ,退出while循環,執行完while循環后,新表中的內容如下圖:
4. 當操作完成,執行查找時,會陷入死循環!
歡迎大家指正!