遍历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异常。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容