码代码的时候发现了这个异常,java.util.ConcurrentModificationException,倒是很熟悉,非线程安全的容器被非法修改了,具体什么原因呢,怎么避免呢,本文简单分析一下,这个小问题其实反映了对容器实现理解的不深刻。

首先,本着从源头找问题的原则,贴一下错误代码:

String str = "test";
Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
while(it.hasNext()){
    Map.Entry<String, String> entry=it.next();
    if (str.equals(params.get(entry.getKey()))) {
        params.remove(entry.getKey());
    }
}

这是一个hashmap的demo,上面可以清晰的看到,在遍历的过程中,符合条件的记录需要被删掉。我们想当然的使用了容器直接remove的方法。这时候得到了java.util.ConcurrentModificationException异常。

定位一下问题,很明显是出在remove这一行。调查了一下,对于非线程安全的容器,这么搞是不可以的,为啥呢,我们先看下Iterator的next()方法:

final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() { return nextNode(); }
    }

final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)//重点在这里
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

找到重点了,抛出异常的地方在nextNode比较modCount和expectedModCount的地方。

那再看下mocCount什么时候增加,增加对象的时候增加很好理解,但是减少的时候的呢,看代码,以下是HashMap.remove(Object) 的实现方法:

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

可以看到modCount增加了,但是没expectedModCount什么事,自然而然也就不想等了。

那我们再看下iterator自带的remove方法:

public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;//update expectedModCount
        }

这里就把expectedModCount更新了。那么对比起来就没问题了。

所以到这里,我们就找到原因所在了。找到问题,解决起来就方便了。

那么简单说一下解决方案吧:

1.使用iterator的remove,是安全的。从上面的代码中可以看出来,不再多说。

2.使用线程安全的ConcurrentHashMap或者Collections.synchronizedMap(Map<k,v>)

 

问题解决了,举一反三的来看,对于其他非线程安全的list,set,map也都使用了fail-fast,也都会有这个问题。使用的时候需要注意了。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐