深入理解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);
}

 

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