1. 程式人生 > >java.util.ConcurrentModificationException 原因分析及解決方案

java.util.ConcurrentModificationException 原因分析及解決方案

碼程式碼的時候發現了這個異常,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,也都會有這個問題。使用的時候需要注意了。