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

背景

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

JDK版本:1.8

探究

點進HashMap源碼發(fā)現(xiàn),在每次循環(huán)結束前碎税,會校驗一下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又是什么呢伟端,結合網(wǎng)上搜索出來的以及源碼注釋的描述,這個參數(shù)是用來在HashMap迭代時匪煌,可以快速發(fā)現(xiàn)錯誤并結束迭代的责蝠。

/**

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

知道這個參數(shù)的含義后,點擊modCount虐杯,查看有哪些地方會修改他的值玛歌。發(fā)現(xiàn)有這些地方會修改modCount。最后賦值為0的方法(reinitialize)是重新初始化HashMap的參數(shù)擎椰,這個可以略過支子。

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()實際調用的方法贯底。在有數(shù)據(jù)被刪除時會修改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是刪除了數(shù)據(jù)惩淳,其他的都是新增數(shù)據(jù)蕉毯。在有這些操作的時候,會導致modCount變化思犁。如果在遍歷HashMap時代虾,進行過如上操作會導致ConcurrentModificationException異常。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末激蹲,一起剝皮案震驚了整個濱河市棉磨,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌学辱,老刑警劉巖乘瓤,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異策泣,居然都是意外死亡衙傀,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門萨咕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來统抬,“玉大人,你說我怎么就攤上這事危队〈辖ǎ” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵茫陆,是天一觀的道長金麸。 經(jīng)常有香客問我,道長簿盅,這世上最難降的妖魔是什么挥下? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任揍魂,我火速辦了婚禮,結果婚禮上棚瘟,老公的妹妹穿的比我還像新娘愉烙。我一直安慰自己,他們只是感情好解取,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著返顺,像睡著了一般禀苦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上遂鹊,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天振乏,我揣著相機與錄音,去河邊找鬼秉扑。 笑死慧邮,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的舟陆。 我是一名探鬼主播误澳,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼秦躯!你這毒婦竟也來了忆谓?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤踱承,失蹤者是張志新(化名)和其女友劉穎倡缠,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體茎活,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡昙沦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了载荔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片盾饮。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖身辨,靈堂內(nèi)的尸體忽然破棺而出丐谋,到底是詐尸還是另有隱情,我是刑警寧澤煌珊,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布号俐,位于F島的核電站,受9級特大地震影響定庵,放射性物質發(fā)生泄漏吏饿。R本人自食惡果不足惜踪危,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望猪落。 院中可真熱鬧贞远,春花似錦、人聲如沸笨忌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽官疲。三九已至袱结,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間途凫,已是汗流浹背垢夹。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留维费,地道東北人果元。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像犀盟,于是被迫代替她去往敵國和親而晒。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容