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 ...
随机推荐
- CSS之页面添加标签
就是因为昨天弄这个“神奇的小标签”差点把自己的园子给废了(情节真的有这么严重),说多了都是泪啊~~(┳_┳).本来是想在页首添加这个“神奇的小标签”的,不知是插件有BUG还是代码错误当场就导致不能编辑 ...
- Java之公约、公倍数
约数和倍数:若整数a能够被b整除,a叫做b的倍数,b就叫做a的约数.公约数:几个数公有的约数,叫做这几个数的公约数:其中最大的一个,叫做这几个数的最大公约数. 那么,我们用编程来看公约数和公倍数: p ...
- C#中调用API
介绍 API( Application Programming Interface ),我想大家不会陌生,它是我们Windows编程的常客,虽然基于.Net平台的C#有了强大的类库,但是,我们还是不能 ...
- 利用 NUget包 EPPlus 实现数据导出到Excel(适用于MVC)
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvoAAABpCAIAAADEEBBGAAAJdElEQVR4nO3cy2ob5wLA8TxKnqTrrr
- CSS3伪类
1.:last-child 比如:查找ul的最后一个li ul li:last-child { //样式 } 2.:first-child 比如:查找ul的第一个li ul li:first-chil ...
- zz linux 下查看局域网内所有存活主机和MAC进址
用namp对局域网扫描一遍,然后查看arp缓存表就可以知道局域内ip-mac的对应了namp比较强大也可以直接扫描mac地址和端口 进行ping扫描,打印出对扫描做出响应的主机: nmap -sP 1 ...
- 内核中读取UTC时间
记录这个知识点的原因是因为项目中需要保存充电日志,因此,趁着这个机会,深入了解一下Linux的时间系统. UTC:(Universal Time Coordinated) 协调世界时的缩写 ...
- mysql安装过程中出现的错误问题解决方案
最近在学Django,因为与数据库相关,所以我下载并安装了MySQL,安装的过程真的是一把辛酸泪啊.安装过后,查看是否可以使用,出现了cann't connect to mysql server这个错 ...
- 真正理解KMP算法
作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4403560.html 所谓KMP算法,就是判断一个模式串是否是一个字符串的子串,通常的算法当 ...
- MYSQL IN 与 EXISTS 的优化示例
文章转载自:http://www.jb51.net/article/53127.htm 当B表的数据集必须小于A表的数据集时,用in优于exists,当A表的数据集系小于B表的数据集时,用exists ...