1. 程式人生 > >ConcurrentModificationException異常原因和解決方法

ConcurrentModificationException異常原因和解決方法

  在前面一篇文章中提到,對Vector、ArrayList在迭代的時候如果同時對其進行修改就會丟擲java.util.ConcurrentModificationException異常。下面我們就來討論以下這個異常出現的原因以及解決辦法。

  以下是本文目錄大綱:

  一.ConcurrentModificationException異常出現的原因

  二.在單執行緒環境下的解決辦法

  三.在多執行緒環境下的解決方法

  若有不正之處請多多諒解,並歡迎批評指正

  請尊重作者勞動成果,轉載請標明原文連結:

  http://www.cnblogs.com/dolphin0520/p/3933551.html

一.ConcurrentModificationException異常出現的原因

  先看下面這段程式碼:

public class Test {
    public static void main(String[] args)  {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(2);
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            Integer integer = iterator.next();
            if(integer==2)
                list.remove(integer);
        }
    }
}

   執行結果:

  

  從異常資訊可以發現,異常出現在checkForComodification()方法中。

  我們不忙看checkForComodification()方法的具體實現,我們先根據程式的程式碼一步一步看ArrayList原始碼的實現:

  首先看ArrayList的iterator()方法的具體實現,檢視原始碼發現在ArrayList的原始碼中並沒有iterator()這個方法,那麼很顯然這個方法應該是其父類或者實現的介面中的方法,我們在其父類AbstractList中找到了iterator()方法的具體實現,下面是其實現程式碼:

public Iterator<E> iterator() {
    return new Itr();
}

   從這段程式碼可以看出返回的是一個指向Itr型別物件的引用,我們接著看Itr的具體實現,在AbstractList類中找到了Itr類的具體實現,它是AbstractList的一個成員內部類,下面這段程式碼是Itr類的所有實現

private class Itr implements Iterator<E> {
    int cursor = 0;
    int lastRet = -1;
    int expectedModCount = modCount;
    public boolean hasNext() {
           return cursor != size();
    }
    public E next() {
           checkForComodification();
        try {
        E next = get(cursor);
        lastRet = cursor++;
        return next;
        } catch (IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
        }
    }
    public void remove() {
        if (lastRet == -1)
        throw new IllegalStateException();
           checkForComodification();
 
        try {
        AbstractList.this.remove(lastRet);
        if (lastRet < cursor)
            cursor--;
        lastRet = -1;
        expectedModCount = modCount;
        } catch (IndexOutOfBoundsException e) {
        throw new ConcurrentModificationException();
        }
    }
 
    final void checkForComodification() {
        if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    }
}

   首先我們看一下它的幾個成員變數:

  cursor:表示下一個要訪問的元素的索引,從next()方法的具體實現就可看出

  lastRet:表示上一個訪問的元素的索引

  expectedModCount:表示對ArrayList修改次數的期望值,它的初始值為modCount。

  modCount是AbstractList類中的一個成員變數

protected transient int modCount = 0;

   該值表示對List的修改次數,檢視ArrayList的add()和remove()方法就可以發現,每次呼叫add()方法或者remove()方法就會對modCount進行加1操作。

  好了,到這裡我們再看看上面的程式:

  當呼叫list.iterator()返回一個Iterator之後,通過Iterator的hashNext()方法判斷是否還有元素未被訪問,我們看一下hasNext()方法,hashNext()方法的實現很簡單:

public boolean hasNext() {
    return cursor != size();
}

   如果下一個訪問的元素下標不等於ArrayList的大小,就表示有元素需要訪問,這個很容易理解,如果下一個訪問元素的下標等於ArrayList的大小,則肯定到達末尾了。

  然後通過Iterator的next()方法獲取到下標為0的元素,我們看一下next()方法的具體實現:

   這裡是非常關鍵的地方:首先在next()方法中會呼叫checkForComodification()方法,然後根據cursor的值獲取到元素,接著將cursor的值賦給lastRet,並對cursor的值進行加1操作。初始時,cursor為0,lastRet為-1,那麼呼叫一次之後,cursor的值為1,lastRet的值為0。注意此時,modCount為0,expectedModCount也為0。

public E next() {
    checkForComodification();
 try {
    E next = get(cursor);
    lastRet = cursor++;
    return next;
 } catch (IndexOutOfBoundsException e) {
    checkForComodification();
    throw new NoSuchElementException();
 }
}

  接著往下看,程式中判斷當前元素的值是否為2,若為2,則呼叫list.remove()方法來刪除該元素。

  我們看一下在ArrayList中的remove()方法做了什麼:

public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}
 
 
private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                numMoved);
    elementData[--size] = null; // Let gc do its work
}

   如果modCount不等於expectedModCount,則丟擲ConcurrentModificationException異常。

  很顯然,此時modCount為1,而expectedModCount為0,因此程式就丟擲了ConcurrentModificationException異常。

  到這裡,想必大家應該明白為何上述程式碼會丟擲ConcurrentModificationException異常了。

  關鍵點就在於:呼叫list.remove()方法導致modCount和expectedModCount的值不一致。

  注意,像使用for-each進行迭代實際上也會出現這種問題。

二.在單執行緒環境下的解決辦法

  既然知道原因了,那麼如何解決呢?

  其實很簡單,細心的朋友可能發現在Itr類中也給出了一個remove()方法:

public void remove() {
    if (lastRet == -1)
    throw new IllegalStateException();
       checkForComodification();
 
    try {
    AbstractList.this.remove(lastRet);
    if (lastRet < cursor)
        cursor--;
    lastRet = -1;
    expectedModCount = modCount;
    } catch (IndexOutOfBoundsException e) {
    throw new ConcurrentModificationException();
    }
}

   在這個方法中,刪除元素實際上呼叫的就是list.remove()方法,但是它多了一個操作:

expectedModCount = modCount;

   因此,在迭代器中如果要刪除元素的話,需要呼叫Itr類的remove方法。

  將上述程式碼改為下面這樣就不會報錯了:

public class Test {
    public static void main(String[] args)  {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(2);
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            Integer integer = iterator.next();
            if(integer==2)
                iterator.remove();   //注意這個地方
        }
    }
}

三.在多執行緒環境下的解決方法

  上面的解決辦法在單執行緒環境下適用,但是在多執行緒下適用嗎?看下面一個例子:

public class Test {
    static ArrayList<Integer> list = new ArrayList<Integer>();
    public static void main(String[] args)  {
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        Thread thread1 = new Thread(){
            public void run() {
                Iterator<Integer> iterator = list.iterator();
                while(iterator.hasNext()){
                    Integer integer = iterator.next();
                    System.out.println(integer);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
        };
        Thread thread2 = new Thread(){
            public void run() {
                Iterator<Integer> iterator = list.iterator();
                while(iterator.hasNext()){
                    Integer integer = iterator.next();
                    if(integer==2)
                        iterator.remove(); 
                }
            };
        };
        thread1.start();
        thread2.start();
    }
}

   執行結果:

  

  有可能有朋友說ArrayList是非執行緒安全的容器,換成Vector就沒問題了,實際上換成Vector還是會出現這種錯誤。

  原因在於,雖然Vector的方法採用了synchronized進行了同步,但是實際上通過Iterator訪問的情況下,每個執行緒裡面返回的是不同的iterator,也即是說expectedModCount是每個執行緒私有。假若此時有2個執行緒,執行緒1在進行遍歷,執行緒2在進行修改,那麼很有可能導致執行緒2修改後導致Vector中的modCount自增了,執行緒2的expectedModCount也自增了,但是執行緒1的expectedModCount沒有自增,此時執行緒1遍歷時就會出現expectedModCount不等於modCount的情況了。

  因此一般有2種解決辦法:

  1)在使用iterator迭代的時候使用synchronized或者Lock進行同步;

  2)使用併發容器CopyOnWriteArrayList代替ArrayList和Vector。

  關於併發容器的內容將在下一篇文章中講述。

  參考資料:

  http://blog.csdn.net/izard999/article/details/6708738

  http://www.2cto.com/kf/201403/286536.html