java.util.ConcurrentModificationException 解决办法(转)
今天在项目的中有一个需求,需要在一个Set类型的集合中删除满足条件的对象,这时想当然地想到直接调用Set的remove(Object o)方法将指定的对象删除即可,测试代码:
public class Test {
public static void main(String[] args) {
User user1 = new User();
user1.setId(1);
user1.setName("zhangsan");
User user2 = new User();
user2.setId(2);
user2.setName("lisi");
Set userSet = new HashSet();
userSet.add(user1);
userSet.add(user2);
for (Iterator it = userSet.iterator(); it.hasNext();) {
User user = (User) it.next();
if (user.getId() == 1) {
userSet.remove(user);
}
if (user.getId() == 2) {
user.setName("zhangsan");
}
}
for(Iterator it = userSet.iterator(); it.hasNext(); ) {
User user = (User) it.next();
System.out.println(user.getId() + "=>" + user.getName());
}
}
}
但运行程序的时候,却发现出错了:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at test.Test.main(Test.java:23)
从API中可以看到List等Collection的实现并没有同步化,如果在多 线程应用程序中出现同时访问,而且出现修改操作的时候都要求外部操作同步化;调用Iterator操作获得的Iterator对象在多线程修改Set的时 候也自动失效,并抛出java.util.ConcurrentModificationException。这种实现机制是fail-fast,对外部 的修改并不能提供任何保证。
网上查找的关于Iterator的工作机制。Iterator是工作在一个独立的线程中,并且拥有一个 mutex锁,就是说Iterator在工作的时候,是不允许被迭代的对象被改变的。Iterator被创建的时候,建立了一个内存索引表(单链表),这个索引表指向原来的对象,当原来的对象数量改变的时候,这个索引表的内容没有同步改变,所以当索引指针往下移动的时候,便找不到要迭代的对象,于是产生错 误。List、Set等是动态的,可变对象数量的数据结构,但是Iterator则是单向不可变,只能顺序读取,不能逆序操作的数据结构,当 Iterator指向的原始数据发生变化时,Iterator自己就迷失了方向。
如何才能满足需求呢,需要再定义一个List,用来保存需要删除的对象:
List delList = new ArrayList();
最后只需要调用集合的removeAll(Collection con)方法就可以了。
public class Test {
public static void main(String[] args) {
boolean flag = false;
User user1 = new User();
user1.setId(1);
user1.setName("shangsan");
User user2 = new User();
user2.setId(2);
user2.setName("lisi");
Set userSet = new HashSet();
userSet.add(user1);
userSet.add(user2);
List delList = new ArrayList();
for (Iterator it = userSet.iterator(); it.hasNext();) {
User user = (User) it.next();
if (user.getId() == 1) {
delList.add(user);
}
if (user.getId() == 2) {
user.setName("zhangsan");
}
}
userSet.removeAll(delList);
for(Iterator it = userSet.iterator(); it.hasNext(); ) {
User user = (User) it.next();
System.out.println(user.getId() + "=>" + user.getName());
}
}
}
其他办法:
还有一种方法,就是在集合remove之前,迭代器也remove,即:
iter.remove();
list.remove(user);
这样就不用新建集合存放了
例:
Iterator.remove() 可以更优雅地实现。
遍历删除元素部分代码更新如下:
for (Iterator it = userSet.iterator(); it.hasNext();) { User user = (User) it.next(); if (user.getId() == 1) { //delList.add(user); it.remove(); } if (user.getId() == 2) { user.setName("zhangsan"); }}//userSet.removeAll(delList); |
java.util.ConcurrentModificationException 解决办法(转)的更多相关文章
- java.util.ConcurrentModificationException 解决办法
在使用iterator.hasNext()操作迭代器的时候,如果此时迭代的对象发生改变,比如插入了新数据,或者有数据被删除. 则使用会报以下异常:Java.util.ConcurrentModific ...
- java.util.ConcurrentModificationException 解决办法(转载)
今天在项目的中有一个需求,需要在一个Set类型的集合中删除满足条件的对象,这时想当然地想到直接调用Set的remove(Object o)方法将指定的对象删除即可,测试代码: public cla ...
- java.util.ConcurrentModificationException解决详解
异常产生 当我们迭代一个ArrayList或者HashMap时,如果尝试对集合做一些修改操作(例如删除元素),可能会抛出java.util.ConcurrentModificationExceptio ...
- intellij idea导入不了java.util.Date解决办法
可以在Settings -> Editor -> General -> Auto Import,将Exclude中的java.util.Date删除.
- java.util.NoSuchElementException解决办法
报错代码 public void switchToNewWindow(){ //得到当前句柄 String currentWindow = driver.getWindowHandle(); //得到 ...
- java.util.ConcurrentModificationException的解决办法
今天在使用iterator.hasNext()操作迭代器的时候,当迭代的对象发生改变,比如插入了新数据,或者有数据被删除. 编译器报出了以下异常: Exception in thread " ...
- java.util.ConcurrentModificationException异常原因及解决方法
在java语言中,ArrayList是一个很常用的类,在编程中经常要对ArrayList进行删除操作,在使用remove方法对ArrayList进行删除操作时,报java.util.Concurren ...
- java.util.ConcurrentModificationException异常的解决
问题复现: List<String> list = new ArrayList<>();list.add("11");list.add("55&q ...
- java.util.ConcurrentModificationException 异常解决的方法及原理
近期在修程序的bug,发现后台抛出下面异常: Exception in thread "main" java.util.ConcurrentModificationExceptio ...
随机推荐
- 苹果系统开发中的混合编程(1):Objective-C和C++的相互调用
首先是OC调用C++的代码. 创建一个Objective-C的项目,并创建c++文件MyCppFile.hpp和MyCppFile.cpp. 把要调用Cpp代码的文件名改成mm后缀名,项目代码 ...
- 对索引像素格式的图片进行Setpixel(具有索引像素格式的图像不支持SetPixel)解决方案
最近编写了一个验证码识别软件.其中对png.jpg图片进行二值化处理时,出现了错误:具有索引像素格式的图像不支持SetPixel解决方案.从字面上来看,这说明我对一个具有索引色的图片进行了直接RGB颜 ...
- 标识域 Identify Field
在对象中保存DB的ID字段,以维持内存对象和DB数据Row之间的identify. 关系DB使用key来区分数据行. 而内存对象不需要这样的键.因为对象系统能够保证身份确认. 读取时没有问题,但是为了 ...
- ProgressIndicator显示进度条以及一些文字信息
//ProgressIndicator可以显示进度条以及一些文字信息,不过这个属性一般都在cs文件中操作. private void PhoneApplicationPage_Loaded(objec ...
- Atan2
在三角函数中,两个参数的函数atan2是正切函数的 一个变种.对于任意不同时等于0的实参数x和y,atan2(y,x)所表达的意思是坐标原点为起点,指向(x,y)的射线在坐标平面上与x轴正方向之间 的 ...
- silverlight 文本框只能输入汉字
private void txtName_KeyDown(object sender, KeyEventArgs e) { Regex rg = new Regex("^[\u4e00-\u ...
- jquery.min.map详见
温故而知新,翻出来阮前辈的文章记录一下 日期:2013年1月23日 上周,jQuery 1.9发布. 这是2.0版之前的最后一个新版本,有很多新功能,其中一个就是支持Source Map. 访问 ht ...
- jquery的相对父元素和相对文档定位示例代码
在开发jquery时候经常需要用到定位,有相对父元素定位和相对文档定位,本文为此总结下,有需要的朋友可以参考下 在开发jquery时候经常需要用到定位,这里概括两种定位: 1.相对父元素定位: $(& ...
- Eclipse使用ButterKnife前,需要的配置步骤
ButterKnife下载地址(7.0.1版本):http://files.cnblogs.com/files/zzw1994/butterknife-7.0.1.zip 官方下载地址(7.0.1版本 ...
- Lambda(2)
Lambda表达式是匿名方法的超集,处理匿名方法有的功能外,还有其他的功能: 1.能够推测出参数的类型,无需显示声明 2.支持语句块和表达式作为方法体 Lambda表达式的书写方式: Lambda表达 ...