java.util.ConcurrentModificationException理解

java.util.ConcurrentModificationException这个异常想必大家都遇到过,

可以通过源码找到根因,容器类,比如ArrayList、HashMap、HashSet,循环方法中可以得知有个modCount发生变化,当同时遍历容器对象,同时增加或者删除元素,就会抛出ConcurrentModificationException,源码如下:

    @Override
    public void forEach(BiConsumer action) {
        Node[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            // Android-changed: Detect changes to modCount early.
            for (int i = 0; (i < tab.length && mc == modCount); ++i) {
                for (Node e = tab[i]; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }
    /**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {
        Node[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; Node 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 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)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;
    }

因此,不要同时遍历容器对象,又同时修改里面的元素,

注意点:

1.这个异常不是只在多线程才会触发,单线程同样会触发,只要满足同时遍历容器对象,又同时修改里面的元素;

2.容器类的迭代器中同时遍历和修改元素,也会触发该异常;

3.打印容器对象时,会调用该对象的toString()方法,这个方法会遍历该容器对象,如果刚好遇到该对象在同时修改元素,也会触发该异常。

你可能感兴趣的:(java,java,kotlin,Concurrent,Modification,Exception)