hashMap是非線程安全的,表如今兩種狀況下:node
1 擴容:數組
t1線程對map進行擴容,此時t2線程來讀取數據,本來要讀取位置爲2的元素,擴容後此元素位置未必是2,則出現讀取錯誤數據。安全
2 hash碰撞併發
兩個線程添加元素髮生hash碰撞,都要將此元素添加到鏈表的頭部,則會發生數據被覆蓋。app
詳情:this
HashMap底層是一個Node數組,一旦發生Hash衝突的的時候,HashMap採用拉鍊法解決碰撞衝突,Node結構:spa
/** * Basic hash bin node, used for most entries. (See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
Node的變量:線程
final int hash; final K key; V value; Node<K,V> next;
執行put方法添加元素後調用此方法:
/** * Implements Map.put and related methods * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) //1位置 此位置爲空,則直接建立newNode tab[i] = newNode(hash, key, value, null); else { //若是此處有元素 Node<K,V> e; K k; //若是此處有元素,且key值相同,則覆蓋元素 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //若是當前位置的元素的結構是樹節點,則將待添加的數據做爲樹節點,添加到紅黑樹結構中 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //剩餘狀況,將新元素追加到當前鏈表元素的next節點 else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //若是鏈表長度達到8,要將鏈表結構轉化爲紅黑樹 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //若是發現相同的key,一樣覆蓋 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
在併發狀況下,添加元素,在 1位置 會出現線程安全問題code
擴容問題:blog
/** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */ final Node<K,V>[] resize() { //舊數據 Node<K,V>[] oldTab = table; //舊map長度 int oldCap = (oldTab == null) ? 0 : oldTab.length; //要調整大小的下一個值 int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { //若是當前數組長度大於等於最大值(1 << 30),就把threshold調到最大,沒法再建立更大的數組了,直接返回原有數據 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } //若是當前長度*2 小於最大值,而且當前長度大於等於默認長度16,閾值*2 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } //若是閾值大於0,則將新數組的長度設置爲閾值=16 else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; // 零初始閾值表示使用默認值 else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) //建立新的數組 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; //將舊數據遷移到新數組 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) //爲每一個不爲空的key從新計算hash值 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; }
線程1在取數據時,map被其它線程擴容,則形成取到錯誤數據