今天研讀Java並發容器和框架時,看到為什么要使用ConcurrentHashMap時,其中有一個原因是:線程不安全的HashMap, HashMap在並發執行put操作時會引起死循環,是因為多線程會導致HashMap的Entry鏈表形成環形數據結構,查找時會陷入死循環。糾起原因看了其他的博客,都比較抽象,所以這里以圖形的方式展示一下,希望支持!
(1)當往HashMap中添加元素時,會引起HashMap容器的擴容,原理不再解釋,直接附源代碼,如下:
1 /** 2 * 3 * 往表中添加元素,如果插入元素之后,表長度不夠,便會調用resize方法擴容 4 */ 5 void addEntry(int hash, K key, V value, int bucketIndex) { 6 Entry<K,V> e = table[bucketIndex]; 7 table[bucketIndex] = new Entry<K,V>(hash, key, value, e); 8 if (size++ >= threshold) 9 resize(2 * table.length); 10 } 11 12 /** 13 * resize()方法如下,重要的是transfer方法,把舊表中的元素添加到新表中 14 */ 15 void resize(int newCapacity) { 16 Entry[] oldTable = table; 17 int oldCapacity = oldTable.length; 18 if (oldCapacity == MAXIMUM_CAPACITY) { 19 threshold = Integer.MAX_VALUE; 20 return; 21 } 22 23 Entry[] newTable = new Entry[newCapacity]; 24 transfer(newTable); 25 table = newTable; 26 threshold = (int)(newCapacity * loadFactor); 27 }
(2)參考上面的代碼,便引入到了transfer方法,(引入重點)這就是HashMap並發時,會引起死循環的根本原因所在,下面結合transfer的源代碼,說明一下產生死循環的原理,先列transfer代碼(這是里JDK7的源偌),如下:
1 /** 2 * Transfers all entries from current table to newTable. 3 */ 4 void transfer(Entry[] newTable, boolean rehash) { 5 int newCapacity = newTable.length; 6 for (Entry<K,V> e : table) { 7 8 while(null != e) { 9 Entry<K,V> next = e.next; ---------------------(1) 10 if (rehash) { 11 e.hash = null == e.key ? 0 : hash(e.key); 12 } 13 int i = indexFor(e.hash, newCapacity); 14 e.next = newTable[i]; 15 newTable[i] = e; 16 e = next; 17 } // while 18 19 } 20 }
(3)假設:
1 Map<Integer> map = new HashMap<Integer>(2); // 只能放置兩個元素,其中的threshold為1(表中只填充一個元素時),即插入元素為1時就擴容(由addEntry方法中得知) 2 //放置2個元素 3 和 7,若要再放置元素8(經hash映射后不等於1)時,會引起擴容
假設放置結果圖如下:
現在有兩個線程A和B,都要執行put操作,即向表中添加元素,即線程A和線程B都會看到上面圖的狀態快照
執行順序如下:
執行一: 線程A執行到transfer函數中(1)處掛起(transfer函數代碼中有標注)。此時在線程A的棧中
1 e = 3 2 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. 當操作完成,執行查找時,會陷入死循環!