HashMap不是線程安全的,多線程寫入修改時可能出現死循環,會致使CPU迅速被佔用至90%。經過源碼能夠看出出現死循環的緣由:數組
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); 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; } } //上面是hashcode相同,key也相等時,替換掉原值,返回老值。 //不然執行下面的操做 modCount++; addEntry(hash, key, value, i); return null; }
出現死循環的代碼部分就從這個addEntry(hash, key, value, i)開始,分析下addEntry(hash, key, value, i)的代碼:安全
void addEntry(int hash, K key, V value, int bucketIndex) { //新元素插入到桶的頭部 Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); //若是元素個數超過閾值,則擴容 if (size++ >= threshold) resize(2 * table.length); }
當元素個數超過閾值則會擴容,擴容時會出現從新hash,下面分析這個擴容的方法resize(2 * table.length):多線程
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]; //將元素轉移到newTable中 transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); }
繼續跟進代碼看這個transfer(newTable)方法的實現:併發
void transfer(Entry[] newTable) { Entry[] src = table; int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { Entry<K,V> e = src[j]; if (e != null) { src[j] = null; do {//這個循環就是引發死循環的罪魁禍首 Entry<K,V> next = e.next; int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } }
下面分析這個do循環,顯得有點繞,其實是一個最節省空間(沒有額外分配任何空間)的一個倒序排列,即把原來Entry數組的一個Entry倒序構建新table的Entry。若是原來某個Entry裏面元素排序是e1--->e2....,線程T1寫入操做引起擴容倒序寫入新table變成了....e2--->e1;線程T2寫入操做時倒序則是e1---->e2....;如此則兩個線程併發寫入時可能會造成一個閉環死循環,會致使CPU迅速佔用100%程序卡死。this