遍歷HashMap時增刪導致報錯問題淺談

背景

在和朋友的一次交談中,朋友遇到了這樣一個問題:在遍歷map時,做了一步remove操作,然后就發生了ConcurrentModificationException異常。由此我點進源碼探究了一番。

JDK版本:1.8

探究

點進HashMap源碼發現,在每次循環結束前,會校驗一下modCount的值,如果modCount變了,就會拋出ConcurrentModificationException異常。

@Override

public void forEach(BiConsumer<? super K, ? super V> action) {

? ? Node<K,V>[] tab;

? ? if (action == null)

? ? ? ? throw new NullPointerException();

? ? if (size > 0 && (tab = table) != null) {

? ? ? ? int mc = modCount;

? ? ? ? for (int i = 0; i < tab.length; ++i) {

? ? ? ? ? ? for (Node<K,V> e = tab[i]; e != null; e = e.next)

? ? ? ? ? ? ? ? action.accept(e.key, e.value);

? ? ? ? }

? ? ? ? if (modCount != mc)

? ? ? ? ? ? throw new ConcurrentModificationException();

? ? }

}

那么modCount又是什么呢,結合網上搜索出來的以及源碼注釋的描述,這個參數是用來在HashMap迭代時,可以快速發現錯誤并結束迭代的。

/**

* The number of times this HashMap has been structurally modified

* Structural modifications are those that change the number of mappings in

* the HashMap or otherwise modify its internal structure (e.g.,

* rehash).? This field is used to make iterators on Collection-views of

* the HashMap fail-fast.? (See ConcurrentModificationException).

*/

transient int modCount;

知道這個參數的含義后,點擊modCount,查看有哪些地方會修改他的值。發現有這些地方會修改modCount。最后賦值為0的方法(reinitialize)是重新初始化HashMap的參數,這個可以略過。

putVal

661行,也是put()實際調用的方法。從源碼中我們可以看到,當key存在時,會直接return oldValue結束方法。也就是說只有在插入新的key時會導致modCount增加。

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)

? ? ? ? tab[i] = newNode(hash, key, value, null);

? ? else {

? ? ? ? Node<K,V> e; K k;

? ? ? ? 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);

? ? ? ? else {

? ? ? ? ? ? for (int binCount = 0; ; ++binCount) {

? ? ? ? ? ? ? ? if ((e = p.next) == null) {

? ? ? ? ? ? ? ? ? ? p.next = newNode(hash, key, value, null);

? ? ? ? ? ? ? ? ? ? if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st

? ? ? ? ? ? ? ? ? ? ? ? treeifyBin(tab, hash);

? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? 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;

}

removeNode

845行,也是remove()實際調用的方法。在有數據被刪除時會修改modCount。

final Node<K,V> removeNode(int hash, Object key, Object value,

? ? ? ? ? ? ? ? ? ? ? ? ? boolean matchValue, boolean movable) {

? ? Node<K,V>[] tab; Node<K,V> p; int n, index;

? ? if ((tab = table) != null && (n = tab.length) > 0 &&

? ? ? ? (p = tab[index = (n - 1) & hash]) != null) {

? ? ? ? Node<K,V> node = null, e; K k; V v;

? ? ? ? if (p.hash == hash &&

? ? ? ? ? ? ((k = p.key) == key || (key != null && key.equals(k))))

? ? ? ? ? ? node = p;

? ? ? ? else if ((e = p.next) != null) {

? ? ? ? ? ? if (p instanceof TreeNode)

? ? ? ? ? ? ? ? node = ((TreeNode<K,V>)p).getTreeNode(hash, key);

? ? ? ? ? ? else {

? ? ? ? ? ? ? ? do {

? ? ? ? ? ? ? ? ? ? if (e.hash == hash &&

? ? ? ? ? ? ? ? ? ? ? ? ((k = e.key) == key ||

? ? ? ? ? ? ? ? ? ? ? ? (key != null && key.equals(k)))) {

? ? ? ? ? ? ? ? ? ? ? ? node = e;

? ? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? p = e;

? ? ? ? ? ? ? ? } while ((e = e.next) != null);

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? if (node != null && (!matchValue || (v = node.value) == value ||

? ? ? ? ? ? ? ? ? ? ? ? ? ? (value != null && value.equals(v)))) {

? ? ? ? ? ? if (node instanceof TreeNode)

? ? ? ? ? ? ? ? ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);

? ? ? ? ? ? else if (node == p)

? ? ? ? ? ? ? ? tab[index] = node.next;

? ? ? ? ? ? else

? ? ? ? ? ? ? ? p.next = node.next;

? ? ? ? ? ? ++modCount;

? ? ? ? ? ? --size;

? ? ? ? ? ? afterNodeRemoval(node);

? ? ? ? ? ? return node;

? ? ? ? }

? ? }

? ? return null;

}

clear

860行。把map里面每一個node都會重置為null。并在調用時就會修改modCount的值。

public void clear() {

? ? Node<K,V>[] tab;

? ? modCount++;

? ? if ((tab = table) != null && size > 0) {

? ? ? ? size = 0;

? ? ? ? for (int i = 0; i < tab.length; ++i)

? ? ? ? ? ? tab[i] = null;

? ? }

}

computeIfAbsent

1142行。該方法會檢測key是否存在,如果不存在則添加且modCount++。

@Override

public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {

? ? if (mappingFunction == null)

? ? ? ? throw new NullPointerException();

? ? int hash = hash(key);

? ? Node<K,V>[] tab; Node<K,V> first; int n, i;

? ? int binCount = 0;

? ? TreeNode<K,V> t = null;

? ? Node<K,V> old = null;

? ? if (size > threshold || (tab = table) == null ||

? ? ? ? (n = tab.length) == 0)

? ? ? ? n = (tab = resize()).length;

? ? if ((first = tab[i = (n - 1) & hash]) != null) {

? ? ? ? if (first instanceof TreeNode)

? ? ? ? ? ? old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

? ? ? ? else {

? ? ? ? ? ? Node<K,V> e = first; K k;

? ? ? ? ? ? do {

? ? ? ? ? ? ? ? if (e.hash == hash &&

? ? ? ? ? ? ? ? ? ? ((k = e.key) == key || (key != null && key.equals(k)))) {

? ? ? ? ? ? ? ? ? ? old = e;

? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ++binCount;

? ? ? ? ? ? } while ((e = e.next) != null);

? ? ? ? }

? ? ? ? V oldValue;

? ? ? ? if (old != null && (oldValue = old.value) != null) {

? ? ? ? ? ? afterNodeAccess(old);

? ? ? ? ? ? return oldValue;

? ? ? ? }

? ? }

? ? V v = mappingFunction.apply(key);

? ? if (v == null) {

? ? ? ? return null;

? ? } else if (old != null) {

? ? ? ? old.value = v;

? ? ? ? afterNodeAccess(old);

? ? ? ? return v;

? ? }

? ? else if (t != null)

? ? ? ? t.putTreeVal(this, tab, hash, key, v);

? ? else {

? ? ? ? tab[i] = newNode(hash, key, v, first);

? ? ? ? if (binCount >= TREEIFY_THRESHOLD - 1)

? ? ? ? ? ? treeifyBin(tab, hash);

? ? }

? ? ++modCount;

? ? ++size;

? ? afterNodeInsertion(true);

? ? return v;

}

compute

1214行。與computeIfAbsen()類似,只會在key不存在且remappingFunction返回的value不為空時進行添加并modCount++。

@Override

public V compute(K key,

? ? ? ? ? ? ? ? BiFunction<? super K, ? super V, ? extends V> remappingFunction) {

? ? if (remappingFunction == null)

? ? ? ? throw new NullPointerException();

? ? int hash = hash(key);

? ? Node<K,V>[] tab; Node<K,V> first; int n, i;

? ? int binCount = 0;

? ? TreeNode<K,V> t = null;

? ? Node<K,V> old = null;

? ? if (size > threshold || (tab = table) == null ||

? ? ? ? (n = tab.length) == 0)

? ? ? ? n = (tab = resize()).length;

? ? if ((first = tab[i = (n - 1) & hash]) != null) {

? ? ? ? if (first instanceof TreeNode)

? ? ? ? ? ? old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

? ? ? ? else {

? ? ? ? ? ? Node<K,V> e = first; K k;

? ? ? ? ? ? do {

? ? ? ? ? ? ? ? if (e.hash == hash &&

? ? ? ? ? ? ? ? ? ? ((k = e.key) == key || (key != null && key.equals(k)))) {

? ? ? ? ? ? ? ? ? ? old = e;

? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ++binCount;

? ? ? ? ? ? } while ((e = e.next) != null);

? ? ? ? }

? ? }

? ? V oldValue = (old == null) ? null : old.value;

? ? V v = remappingFunction.apply(key, oldValue);

? ? if (old != null) {

? ? ? ? if (v != null) {

? ? ? ? ? ? old.value = v;

? ? ? ? ? ? afterNodeAccess(old);

? ? ? ? }

? ? ? ? else

? ? ? ? ? ? removeNode(hash, key, null, false, true);

? ? }

? ? else if (v != null) {

? ? ? ? if (t != null)

? ? ? ? ? ? t.putTreeVal(this, tab, hash, key, v);

? ? ? ? else {

? ? ? ? ? ? tab[i] = newNode(hash, key, v, first);

? ? ? ? ? ? if (binCount >= TREEIFY_THRESHOLD - 1)

? ? ? ? ? ? ? ? treeifyBin(tab, hash);

? ? ? ? }

? ? ? ? ++modCount;

? ? ? ? ++size;

? ? ? ? afterNodeInsertion(true);

? ? }

? ? return v;

}

merge

1273行。如果key不存在,則會添加key-value且modCount++。

@Override

public V merge(K key, V value,

? ? ? ? ? ? ? BiFunction<? super V, ? super V, ? extends V> remappingFunction) {

? ? if (value == null)

? ? ? ? throw new NullPointerException();

? ? if (remappingFunction == null)

? ? ? ? throw new NullPointerException();

? ? int hash = hash(key);

? ? Node<K,V>[] tab; Node<K,V> first; int n, i;

? ? int binCount = 0;

? ? TreeNode<K,V> t = null;

? ? Node<K,V> old = null;

? ? if (size > threshold || (tab = table) == null ||

? ? ? ? (n = tab.length) == 0)

? ? ? ? n = (tab = resize()).length;

? ? if ((first = tab[i = (n - 1) & hash]) != null) {

? ? ? ? if (first instanceof TreeNode)

? ? ? ? ? ? old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

? ? ? ? else {

? ? ? ? ? ? Node<K,V> e = first; K k;

? ? ? ? ? ? do {

? ? ? ? ? ? ? ? if (e.hash == hash &&

? ? ? ? ? ? ? ? ? ? ((k = e.key) == key || (key != null && key.equals(k)))) {

? ? ? ? ? ? ? ? ? ? old = e;

? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ++binCount;

? ? ? ? ? ? } while ((e = e.next) != null);

? ? ? ? }

? ? }

? ? if (old != null) {

? ? ? ? V v;

? ? ? ? if (old.value != null)

? ? ? ? ? ? v = remappingFunction.apply(old.value, value);

? ? ? ? else

? ? ? ? ? ? v = value;

? ? ? ? if (v != null) {

? ? ? ? ? ? old.value = v;

? ? ? ? ? ? afterNodeAccess(old);

? ? ? ? }

? ? ? ? else

? ? ? ? ? ? removeNode(hash, key, null, false, true);

? ? ? ? return v;

? ? }

? ? if (value != null) {

? ? ? ? if (t != null)

? ? ? ? ? ? t.putTreeVal(this, tab, hash, key, value);

? ? ? ? else {

? ? ? ? ? ? tab[i] = newNode(hash, key, value, first);

? ? ? ? ? ? if (binCount >= TREEIFY_THRESHOLD - 1)

? ? ? ? ? ? ? ? treeifyBin(tab, hash);

? ? ? ? }

? ? ? ? ++modCount;

? ? ? ? ++size;

? ? ? ? afterNodeInsertion(true);

? ? }

? ? return value;

}

總結

HashMap當中有7處地方對modCount進行了重新賦值,其中reinitialize和clear方法相當于重置了整個HashMap,removeNode是刪除了數據,其他的都是新增數據。在有這些操作的時候,會導致modCount變化。如果在遍歷HashMap時,進行過如上操作會導致ConcurrentModificationException異常。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容