前几天项目整合的时候,在服务器上测试我负责的功能的时候,出现了一个Exception,之前我本地测试的时候未测试出来。异常信息:java.util.ConcurrentModificationException
老大一眼就看出来了,说是在对List集合遍历的时候,使用了ArrayList的remove(Object o)方法。下面是测试出现异常的方法:
package com.day0219.list;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author xukai
* 测试List集合在循环的时候,使用remove(Object o)方法
*/
public class TestList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 添加元素
for(int i = 1; i < 100; i++){
list.add("str_" + i);
}
// 使用foreach循环遍历List,同时remove某个条件的元素
for(String str : list){
// 带偶数的remove
if(Integer.parseInt(str.substring(4)) % 2 == 0){
list.remove(str);
}
}
// 使用Iterator遍历List
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String str = iterator.next();
if(Integer.parseInt(str.substring(4)) % 2 == 0){
list.remove(str);
}
}
// 打印List
for(String str : list){
System.out.println(list.indexOf(str) + "," + str);
}
}
}
这里使用了两种遍历集合的办法。
前者是jdk5.0新增加的一个循环结构,可以用来处理集合中的每个元素而不用考虑集合下标,格式如下:
for(vaiable : collection) { statement; }
定义一个变量用于暂存集合中的每一个元素,并执行相应的语句块。collection必须是一个数组或者是一个实现了Iterable接口的类对象。
后者使用接口Iterable,实现这个接口允许对象成为 "foreach" 语句的目标。方法iterator(),返回一个在一组 T 类型的元素上进行迭代的迭代器。
两者在使用remove(Object o)方法的时候都会出现异常java.util.ConcurrentModificationException。根据后者分析,方便理解。
异常出现的位置:
可以看到iterator()方法是在ArrayList的父类AbstractList中实现的:
public Iterator<E> iterator() {
return new 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 {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet < 0)
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();
}
}
字段解释:
protected transient int modCount = 0;
已
从结构上修改 此列表的次数。从结构上修改是指更改列表的大小,或者打乱列表,从而使正在进行的迭代产生错误的结果。此字段由
iterator
和
listIterator
方法返回的迭代器和列表迭代器实现使用。如果意外更改了此字段中的值,则迭代器(或列表迭代器)将抛出
ConcurrentModificationException
来响应
next
、
remove
、
previous
、
set
或
add
操作。在迭代期间面临并发修改时,它提供了
快速失败 行为,而不是非确定性行为。
以上为API中文翻译,即异常出现的原因。
下面是异常出现的过程:
list.iterator() //创建一个Itr()类对象,初始化数据
cursor = 0; // 游标
lastRet = -1; // 上一个索引的位置
expectedModCount = 0; // 迭代器认为后面列表应该有modCount的值。如果这个预期被破坏,迭代器检测到并发修改。
iterator.hasNext(); // 判断游标位置是否等于集合大小,等于返回false
iterator.next(); // 向下一个移动
执行checkForComodification(),通过。
list.remove(Object o);
该方法的实现:
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;
}
实际执行为fastRemove(index);
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
}
可以看到首先modCount++,值发生改变,最后把删除的元素的内存地址设置为NULL,方便GC回收。
当下一次执行 next()方法的时候,checkForComodification()的判断:
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
抛出异常。
使用foreach遍历集合的原理是相同的,因为foreach循环其实是由Iterator实现的。同样会执行next()方法进行校验,出现同样的异常。
解决:使用iterator.remove()方法
Itr()内部方法
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
这里执行了expectedModCount = modCount;防止出现异常
while(iterator.hasNext()){
String str = iterator.next();
if(Integer.parseInt(str.substring(4)) % 2 == 0){
iterator.remove(); // 变化了
}
}
如果想使用foreach循环遍历,并且删除,可以重新创建一个List集合用来装
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// 添加元素
for(int i = 1; i < 100; i++){
list.add("str_" + i);
}
List<String> temp = new ArrayList<>();
// 使用foreach循环遍历List,同时remove某个条件的元素
for(String str : list){
// 带偶数的remove
if(Integer.parseInt(str.substring(4)) % 2 != 0){
temp.add(str);
}
}
list = null;// GC回收
// 打印List
for(String str : temp){
System.out.println(temp.indexOf(str) + "," + str);
}
}
*注:以上测试都是在单线程环境下