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 ...
随机推荐
- 检测是否支持HTML5中的Video标签
//检测是否支持HTML5 function checkVideo() { if (!!document.createElement('video').canPlayType) { var vidTe ...
- QtPropertyBrowser+vs2010的安装与配置(转)
这一篇文章有些问题,后又写了一篇,地址是http://www.cnblogs.com/aminxu/p/4552410.html 转自http://blog.csdn.net/jingwenlai_s ...
- Spring中Quartz的配置
Quartz是一个强大的企业级任务调度框架,Spring中继承并简化了Quartz,下面就看看在Spring中怎样配置Quartz: 首先,来写一个测试被调度的类:(QuartzHelloWorldJ ...
- Oracle在所有内容前追加一些内容的方法
参照下面的sql语句. SQL> SELECT * FROM UserInfo; NAME CHINESE -------------------- ...
- Android实现Http协议案例
在Android开发中,使用Http协议实现网络之间的通信是随处可见的,使用http方式主要采用2中请求方式即get和post两种方式. 一.使用get方式: HttpGet httpGet = ne ...
- LLVM language 参考手册(译)(6)
模块级内联汇编(Module-Level Inline Assembly) 模块包含“module-level inline assembly”块,这与GCC中的“file scope inline ...
- Windows Phone 8 蓝牙编程
蓝牙是手机的近距离无限传输的技术,在之前的Windows Phone 7系统手机里面仅支持蓝牙耳机功能,并不支持蓝牙文件信息传输,那么在Windows Phone 8手机里面将全面支持蓝牙技术,并且提 ...
- LVS-HA
heartbeat 监听在udp的694的端口 LRM:本地资源管理器 CRM:资源管理器 RA:资源代理(脚本) heartbeat legacy : heartbeat 传统类型的资源代理,通 ...
- javascript里面技巧整理
web develop tools secrets: http://jinlong.github.io/blog/2013/08/29/devtoolsecrets/ 1.Date new Date( ...
- MyEclipse中新建html5中文乱码
近期刚开始入门html5 和 javascript 用MyEclipse2104创建html5时,遇到浏览器显示中文乱码的问题 [MyEclipse中设置的html5,jsp编码都采用的UTF-8] ...