深入理解ConcurrentModificationException併發修改異常

深入理解ConcurrentModificationException併發修改異常

 

我是一個雙非二本院校軟件工廠專業的學生,自學Java6個月

接下來一段時間,我將以複習的形式,總結所學知識,同時進行輸出,形成自己的知識體系。

雞湯:那麼多學技術的都可以成功,憑什麼你不行?

 

 

我們先來看兩個案例:

/**
 * @ClassName: ConcurrentModificationExceptionDemo
 * @description: 併發修改異常案例1
 * @author: XZQ
 * @create: 2020/3/27 22:41
 **/
public class ConcurrentModificationExceptionDemo1 {
    public static void main(String[] args) {
        final ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
​
        final Iterator<Integer> iterator = list.iterator();
​
        while (iterator.hasNext()) {
            if (iterator.next().equals(1)) {
                list.remove(1);
            }
        }
    }
}
public class ConcurrentModificationExceptionDemo2 {
    public static void main(String[] args) {
        final ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
​
        for (Integer i : list) {
            if (i.equals(1)) {
                list.remove(i);
            }
        }
    }
}

程序執行結果:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at com.xzq.collectionsafe.ConcurrentModificationExceptionDemo.main(ConcurrentModificationExceptionDemo.java:18)
​
Process finished with exit code 1

可以看到,上面的代碼出現了併發修改異常,乍一看好像由沒有什麼毛病,相信很多同學都遇到過這個問題,我決定深入探究一下出現異常的原因以及如何解決。

 

一、ConcurrentModificationException出現原因

出現異常,我們可以先看控制檯顯示的異常信息,由上面的異常信息可以看到異常出現在checkForComodification(ArrayList.java:901)

找到checkForComodification()方法如下

final void checkForComodification() {
    if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
}

可以看到是因爲 modCount != expectedModCount 導致,修改的次數 不等於 期待修改的次數 那爲什麼會出現這樣的情況?

先來看看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; //表示下一個要訪問的元素的索引,從next()方法的具體實現就可看出
    int lastRet = -1;//表示上一個訪問的元素的索引
    int expectedModCount = modCount;//表示對ArrayList修改次數的期望值,它的初始值爲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()方法的具體實現:

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

這裏是非常關鍵的地方:

首先,在next()方法中會調用checkForComodification()方法(此時 expectedModCount = modCount = 0),然後根據cursor的值獲取到元素,接着將cursor的值賦給lastRet,並對cursor的值進行加1操作。初始時,cursor爲0,lastRet爲-1,那麼調用一次之後,cursor的值爲1,lastRet的值爲0。注意此時,modCount爲0,expectedModCount也爲0。

接着往下看

程序中判斷當前元素的值是否爲1,若爲1,則調用list.remove()方法來刪除該元素。(注意,是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);//從index+1開始向前移動numMoved位
    elementData[--size] = null; // Let gc do its work
}

通過remove方法刪除元素最終是調用的fastRemove()方法,在fastRemove()方法中,首先對modCount進行加1操作(因爲對集合修改了一次),然後接下來就是刪除元素的操作,最後將size進行減1操作,並將引用置爲null以方便垃圾收集器進行回收工作,防止造成內存泄漏。

那麼注意此時各個變量的值:對於iterator,其expectedModCount爲0,cursor的值爲1,lastRet的值爲0。

對於list,其modCount爲1,size爲0。

接着看程序代碼,執行完刪除操作後,繼續while循環,調用hasNext方法()判斷,由於此時cursor爲1,而size爲0,那麼返回true,所以繼續執行while循環,然後繼續調用iterator的next()方法:

注意,此時要注意next()方法中的第一句:checkForComodification()。

在checkForComodification方法中進行的操作是:

final void checkForComodification() {
    if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
}

如果modCount不等於expectedModCount,則拋出ConcurrentModificationException異常。

很顯然,此時modCount爲1,而expectedModCount爲0,因此程序就拋出了ConcurrentModificationException異常。

到這裏,想必大家應該明白爲何上述代碼會拋出ConcurrentModificationException異常了。

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

注意,使用普通for循環進行迭代實際上也會出現這種問題。

 

二、單線程環境下解決方案

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

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

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

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

expectedModCount = modCount;

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

將上述代碼改爲下面這樣就不會報錯了:

public class ConcurrentModificationExceptionDemo {
    public static void main(String[] args) {
        final ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
​
        final Iterator<Integer> iterator = list.iterator();
​
        while (iterator.hasNext()) {
            if (iterator.next().equals(1)) {
//                list.remove(1);
                iterator.remove();
            }
        }
        System.out.println(list);
    }
}

 

三、多線程環境下的解決方案

上面的解決方案只適用於單線程,而多線程就不適用了,詳情看如下代碼

public class ConcurrentModificationExceptionDemo2 {
    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() {
            @Override
            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() {
            @Override
            public void run() {
                Iterator<Integer> iterator = list.iterator();
                while (iterator.hasNext()) {
                    Integer integer = iterator.next();
                    if (integer == 2)
                        iterator.remove();
                }
            }
​
            ;
        };
        thread1.start();
        thread2.start();
    }
}

程序執行結果:

1
Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at com.xzq.collectionsafe.ConcurrentModificationExceptionDemo2$1.run(ConcurrentModificationExceptionDemo2.java:26)

有可能有同學說ArrayList是非線程安全的容器,換成Vector就沒問題了,實際上換成Vector還是會出現這種錯誤。

原因在於,雖然Vector的方法採用了synchronized進行了同步,但是由於Vector是繼承的AbstarctList,因此通過Iterator來訪問容器的話,事實上是不需要獲取鎖就可以訪問。那麼顯然,由於使用iterator對容器進行訪問不需要獲取鎖,在多線程中就會造成當一個線程刪除了元素,由於modCount是AbstarctList的成員變量,因此可能會導致在其他線程中modCount和expectedModCount值不等。

就比如上面的代碼中,很顯然iterator是線程私有的,

初始時,線程1和線程2中的modCount、expectedModCount都爲0,

當線程2通過iterator.remove()刪除元素時,會修改modCount值爲1,並且會修改線程2中的expectedModCount的值爲1,

而此時線程1中的expectedModCount值爲0,雖然modCount不是volatile變量,不保證線程1一定看得到線程2修改後的modCount的值,但是也有可能看得到線程2對modCount的修改,這樣就有可能導致線程1中比較expectedModCount和modCount不等,而拋出異常。

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

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

public class ConcurrentModificationExceptionDemo2 {
    static ArrayList<Integer> list = new ArrayList<Integer>();
    static Object object = new Object();
​
    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(() -> {
            synchronized (object) {
                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(() -> {
            synchronized (object) {
                Iterator<Integer> iterator = list.iterator();
                while (iterator.hasNext()) {
                    Integer integer = iterator.next();
                    if (integer == 2) {
                        iterator.remove();
                    }
                }
            }
        });
​
        thread1.start();
        thread2.start();
    }
}

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

public class ConcurrentModificationExceptionDemo2 {
    static List list = new CopyOnWriteArrayList<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(() -> {
            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(() -> {
            Iterator<Integer> iterator = list.iterator();
            while (iterator.hasNext()) {
                Integer integer = iterator.next();
                if (integer == 2) {
//                    iterator.remove();
                    list.remove(integer);
                }
            }
        });
​
        thread1.start();
        thread2.start();
    }
}

注意:CopyOnWriteArrayList不支持

while (iterator.hasNext()) { 
    iterator.remove(); 
} 

原因:CopyOnWriteArrayList在做迭代之前是做了一份”快照”,所以此時的iter是不可變的,也就是說假設在此遍歷中調用iter.remove()會拋出異常 解決的方法:

CopyOnWriteArrayList<T> t1 ;
Iterator<GameExperience> iterator = t1.iterator();
while (iterator.hasNext()) {
    T t= iterator.next();
    t1.remove(t);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章