大家应该都知道, 在java中, 在对一些集合迭代的过程中对集合进行一些修改的操作, 比如说add,remove之类的操作, 搞不好就会抛ConcurrentModificationException
,
前几天碰到了这个异常
在单线程操作的情况下,要求:遍历数据集合,判断不符合条件的元素,做删除操作。
在用foreach和 Iterator 都会发生java.util.ConcurrentModificationException
。
foreach的实现原理
foreach之所以能工作,是因为这些集合类都实现了Iterable接口,该接口中定义了Iterator迭代器的产生方法,并且foreach就是通过Iterable接口在序列中进行移动。
我们来看一下foreach反编译后的代码
/**
*@description 用来测试forEach的方法
*@author SongHongWei
*@params
*@time 2018/8/28-11:47
**/
public static void testFor()
{
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
for (String str : list)
{
System.out.println(str);
}
}
/**
*@description 用来测试数组使用forEach
*@author SongHongWei
*@params
*@time 2018/8/28-14:04
**/
public static void testArray()
{
String[] arrays = {"1111", "22222"};
for (String array : arrays)
{
System.out.println(array);
}
}
反编译后的
public static void testFor() {
List<String> list = new ArrayList();
list.add("111");
list.add("222");
Iterator i$ = list.iterator();
while(i$.hasNext()) {
String str = (String)i$.next();
System.out.println(str);
}
}
public static void testArray() {
String[] arrays = new String[]{"1111", "22222"};
String[] arr$ = arrays;
int len$ = arrays.length;
for(int i$ = 0; i$ < len$; ++i$) {
String array = arr$[i$];
System.out.println(array);
}
}
但是需要注意的是:虽然实现了java.lang.Iterable
接口的对象可以用forEach去遍历,但是能用forEach去遍历的不一定实现了该接口
看一下JavaDoc对java.util.ConcurrentModificationException
异常的描述:当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
查看源码后终于发现了原因是因为:
迭代器的modCount
和expectedModCount
的值不一致。
单线程中该异常出现的原因是:对一个集合遍历的同时,有对该集合进行了增或者删的操作。导致AbstarctLis
t的modCount
和expectedModCount
的值不一致。
而我们要做的就是将需要操作的元素放到中间元素中,并记录操作标志位。在遍历结束后进行增删操作。
或自定义迭代器复写其中的相关操作,在操作结束后添加expectedModCount = modCount;
多线程中更容易出现该异常,当你在一个线程中对一数据集合进行遍历,正赶上另外一个线程对该数据集合进行增删操作。
解决方案:
在使用iterator迭代的时候使用synchronized或者Lock进行同步。
使用并发容器CopyOnWriteArrayList代替ArrayList和Vector。
以下是Demo:
推荐大家
1、使用for循环进行遍历集合,在for循环中做增删操作。
2、用Iterator遍历,使用iterator.remove().
package com.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
/*
* 这种方式会导致出现java.util.ConcurrentModificationException异常
* 原因在于:对List采用的是foreach遍历操作,并且遍历过程中对list进行了删除操作,
* 导致Iterator在执行next()方法时调用 checkForComodification()方法
* 接着将cursor的值赋给lastRet,并对cursor的值进行操作
*/
public List<String> m1(List<String> list) {
for (String temp : list) {
if ("3".equals(temp)) {
list.remove(temp);
}
}
return list;
}
public List<String> m2(List<String> list) {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String temp = iterator.next();
if ("2".equals(temp)) {
//list.remove(temp);// 出现java.util.ConcurrentModificationException
/*
*直接使用迭代器的remove方法可以避免ConcurrentModificationException异常出现
*/
iterator.remove();
}
}
return list;
}
/*
*不适用foreach遍历循环也可避免
*/
public List<String> m3(List<String> list) {
for (int i = 0; i < list.size(); i++) {
if ("2".equals(list.get(i))) {
list.remove(i);
}
}
return list;
}
/*
* 测试方法
*/
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
Test test = new Test();
List<String> listTemp = test.m2(list);
System.out.println(listTemp.toString());
}
}