【软件构造】第十章
在做lab6时,实现GUI的过程中,遇到了java.util.ConcurrentModificationException异常,本文讲述了java.util.ConcurrentModificationException异常产生的原因,以及如何处理该异常。
一.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);
}
}
}
这段代码就会产生ConcurrentModificationException异常。
对于ArrayList的iterator()方法是其父类AbstractList中的方法,其具体实现如下:
public Iterator<E> iterator() {
return new Itr();
}
该方法返回的是一个指向Itr类型对象的引用,我们接着看Itr的具体实现,在AbstractList类中找到了Itr类的具体实现,它是AbstractList的一个成员内部类:
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类中的一个成员变量,初始化为0。表示对List的修改次数,查看ArrayList的add()和remove()方法就可以发现,每次调用add()方法或者remove()方法就会对modCount进行加1操作。
回到开头的程序中,依次看下Iterator的hasNext()方法、next()方法:
public boolean hasNext() { return cursor != size(); }
hasNext()方法:如果下一个访问的元素下标不等于ArrayList的大小,就表示有元素需要访问
public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }
next()方法:首先在next()方法中会调用checkForComodification()方法,然后根据cursor的值获取到元素,接着将cursor的值赋给lastRet,并对cursor的值进行加1操作。
接着在开头的程序中要判断当前元素的值是否为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 }
通过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为1,那么返回true,所以继续执行while循环,然后继续调用iterator的next()方法:
注意,此时要注意next()方法中的第一句:checkForComodification()。
很显然,此时modCount为1,而expectedModCount为0,因此程序就抛出了ConcurrentModificationException异常。
所以抛出这个异常的关键点就在于:调用list.remove()方法导致modCount和expectedModCount的值不一致。
注意,像使用for-each进行迭代实际上也会出现这种问题。
二.在单线程环境下的解决办法
所以对于单线程来说,消除这个异常只需要使用Itr类的remove方法。因为它多了一个操作:
expectedModCount = modCount;
这样就可以保证这两个数值相等从而不会报错了。
三.在多线程环境下的解决办法
考虑下面的代码:
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(); } }
结果会报ConcurrentModificationException异常,即使将Arraylist换成线程安全的容器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。
参考:https://www.cnblogs.com/dolphin0520/p/3933551.html