Java ConcurrentModificationException解决方案
为什么会抛出java.util.ConcurrentModificationException异常
(如有错误,欢迎指正)
先看一下这一段代码,看起来没有什么问题 但是运行会出现以下异常
首先java的foreach循环其实就是根据list对象创建一个Iterator迭代对象,用这个迭代对象来遍历list,相当于list对象中元素的遍历托管给了Iterator,你如果要对list进行增删操作,都必须经过Iterator,否则Iterator遍历时会乱,所以直接对list进行删除时,Iterator会抛出ConcurrentModificationException异常
其实,每次foreach迭代的时候都有两部操作:
- iterator.hasNext() //判断下个元素是否存在
- info= iterator.next() //将下个元素赋值给info
一些相关的方法的代码如下:
首先看ArrayList的iterator()方法:
public Iterator<E> iterator() {
return new Itr();
}
从这段代码可以看出返回的是一个指向Itr类型对象的引用,我们接着看Itr()方法:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
几个成员变量解释如下:
- cursor:表示下一个要访问的元素的索引
- lastRet:表示上一个访问的元素的索引
- expectedModCount:Iterator:期望这个list被修改的次数,初始值为modCount
- modCount:表示对list的修改次数,当调用List的add或者remove方法的时候,这个modCount加一或减一
当调用list.iterator()之后,通过hashNext()方法判断是否还有元素未被访问,hasNext()方法实现如下:
public boolean hasNext() {
return cursor != size;
}
然后通过进到next()方法,next()方法的具体实现:
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
这里首先会调用 checkForComodification()方法,然后将下一个元素的索引赋值给i并且检验i的大小抛出对应异常,若i的范围值正确,sursor+1;并且将此时的索引值i赋值给lastRet ,初始时cursor为0,lastRet为-1,调用一次之后,此时的cursor的值为1,lastRet的值为0。
再看一下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; // clear to 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
那么为什么modCount 不等于expectedModCount了呢?
iterator创建的时候,modCount被赋值给了expectedModCount,但是调用add和remove方法的时候不会同时自动增减expectedModCount。
调用list.remove()方法导致modCount和expectedModCount的值不一致。
解决方案如下
查看源码知道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方法就不会报错
单线程下解决方案
将之前的代码如下修改即可