【转】Java ConcurrentModificationException 异常分析与解决方案--还不错
原文网址:http://www.2cto.com/kf/201403/286536.html
-

一、单线程
1. 异常情况举例
只要抛出出现异常,可以肯定的是代码一定有错误的地方。先来看看都有哪些情况会出现ConcurrentModificationException异常,下面以ArrayList remove 操作进行举例:
使用的数据集合:
1234567List<string> myList =newArrayList<string>();myList.add("1");myList.add("2");myList.add("3");myList.add("4");myList.add("5");</string></string>以下三种情况都会出现异常:
12345678910111213141516171819202122Iterator<string> it = myList.iterator();while(it.hasNext()) {String value = it.next();if(value.equals("3")) {myList.remove(value);// error}}for(Iterator<string> it = myList.iterator(); it.hasNext();) {String value = it.next();if(value.equals("3")) {myList.remove(value);// error}}for(String value : myList) {System. out.println("List Value:"+ value);if(value.equals("3")) {myList.remove(value);// error}} </string></string>异常信息如下:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)2. 根本原因
以上都有3种出现异常的情况有一个共同的特点,都是使用Iterator进行遍历,且都是通过ArrayList.remove(Object) 进行删除操作。
想要找出根本原因,直接查看ArrayList源码看为什么出现异常:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960publicclassArrayList<e>extendsAbstractList<e>implementsCloneable, Serializable, RandomAccess {@Overridepublicbooleanremove(Object object) {Object[] a = array;ints = size;if(object !=null) {for(inti =0; i < s; i++) {if(object.equals(a[i])) {System.arraycopy(a, i +1, a, i, --s - i);a[s] =null;// Prevent memory leaksize = s;modCount++;// 只要删除成功都是累加returntrue;}}}else{for(inti =0; i < s; i++) {if(a[i] ==null) {System.arraycopy(a, i +1, a, i, --s - i);a[s] =null;// Prevent memory leaksize = s;modCount++;// 只要删除成功都是累加returntrue;}}}returnfalse;}@OverridepublicIterator<e> iterator() {returnnewArrayListIterator();}privateclassArrayListIteratorimplementsIterator<e> {......// 全局修改总数保存到当前类中/** The expected modCount value */privateintexpectedModCount = modCount;@SuppressWarnings("unchecked")publicE next() {ArrayList<e> ourList = ArrayList.this;intrem = remaining;// 如果创建时的值不相同,抛出异常if(ourList.modCount != expectedModCount) {thrownewConcurrentModificationException();}if(rem ==0) {thrownewNoSuchElementException();}remaining = rem -1;return(E) ourList.array[removalIndex = ourList.size - rem];}......}} </e></e></e></e></e>List、Set、Map 都可以通过Iterator进行遍历,这里仅仅是通过List举例,在使用其他集合遍历时进行增删操作都需要留意是否会触发ConcurrentModificationException异常。
3. 解决方案
上面列举了会出现问题的几种情况,也分析了问题出现的根本原因,现在来总结一下怎样才是正确的,如果避免遍历时进行增删操作不会出现ConcurrentModificationException异常。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950// 1 使用Iterator提供的remove方法,用于删除当前元素for(Iterator<string> it = myList.iterator(); it.hasNext();) {String value = it.next();if(value.equals("3")) {it.remove();// ok}}System. out.println("List Value:"+ myList.toString());// 2 建一个集合,记录需要删除的元素,之后统一删除List<string> templist =newArrayList<string>();for(String value : myList) {if(value.equals("3")) {templist.remove(value);}}// 可以查看removeAll源码,其中使用Iterator进行遍历myList.removeAll(templist);System. out.println("List Value:"+ myList.toString());// 3. 使用线程安全CopyOnWriteArrayList进行删除操作List<string> myList =newCopyOnWriteArrayList<string>();myList.add("1");myList.add("2");myList.add("3");myList.add("4");myList.add("5");Iterator<string> it = myList.iterator();while(it.hasNext()) {String value = it.next();if(value.equals("3")) {myList.remove("4");myList.add("6");myList.add("7");}}System. out.println("List Value:"+ myList.toString());// 4. 不使用Iterator进行遍历,需要注意的是自己保证索引正常for(inti =0; i < myList.size(); i++) {String value = myList.get(i);System. out.println("List Value:"+ value);if(value.equals("3")) {myList.remove(value);// oki--;// 因为位置发生改变,所以必须修改i的位置}}System. out.println("List Value:"+ myList.toString());</string></string></string></string></string></string>输出结果都是:List Value:[1, 2, 4, 5] , 不会出现异常。
以上4种解决办法在单线程中测试完全没有问题,但是如果在多线程中呢?二、多线程
1. 同步异常情况举例
上面针对ConcurrentModificationException异常在单线程情况下提出了4种解决方案,本来是可以很哈皮的洗洗睡了,但是如果涉及到多线程环境可能就不那么乐观了。
下面的例子中开启两个子线程,一个进行遍历,另外一个有条件删除元素:12345678910111213141516171819202122232425262728293031323334353637383940finalList<string> myList = createTestData();newThread(newRunnable() {@Overridepublicvoidrun() {for(String string : myList) {System.out.println("遍历集合 value = "+ string);try{Thread.sleep(100);}catch(InterruptedException e) {e.printStackTrace();}}}}).start();newThread(newRunnable() {@Overridepublicvoidrun() {for(Iterator<string> it = myList.iterator(); it.hasNext();) {String value = it.next();System.out.println("删除元素 value = "+ value);if(value.equals("3")) {it.remove();}try{Thread.sleep(100);}catch(InterruptedException e) {e.printStackTrace();}}}}).start();</string></string>输出结果:
遍历集合 value = 1
删除元素 value = 1
遍历集合 value = 2
删除元素 value = 2
遍历集合 value = 3
删除元素 value = 3
Exception in thread "Thread-0" 删除元素 value = 4
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at list.ConcurrentModificationExceptionStudy$1.run(ConcurrentModificationExceptionStudy.java:42)
at java.lang.Thread.run(Unknown Source)
删除元素 value = 5结论:
上面的例子在多线程情况下,仅使用单线程遍历中进行删除的第1种解决方案使用it.remove(),但是测试得知4种的解决办法中的1、2、3依然会出现问题。
接着来再看一下JavaDoc对java.util.ConcurrentModificationException异常的描述:
当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
说明以上办法在同一个线程执行的时候是没问题的,但是在异步情况下依然可能出现异常。2. 尝试方案
(1) 在所有遍历增删地方都加上synchronized或者使用Collections.synchronizedList,虽然能解决问题但是并不推荐,因为增删造成的同步锁可能会阻塞遍历操作。
(2) 推荐使用ConcurrentHashMap或者CopyOnWriteArrayList。3. CopyOnWriteArrayList注意事项
(1) CopyOnWriteArrayList不能使用Iterator.remove()进行删除。
(2) CopyOnWriteArrayList使用Iterator且使用List.remove(Object);会出现如下异常:
java.lang.UnsupportedOperationException: Unsupported operation remove
at java.util.concurrent.CopyOnWriteArrayList$ListIteratorImpl.remove(CopyOnWriteArrayList.java:804)4. 解决方案
单线程情况下列出4种解决方案,但是发现在多线程情况下仅有第4种方案才能在多线程情况下不出现问题。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546List<string> myList =newCopyOnWriteArrayList<string>();myList.add("1");myList.add("2");myList.add("3");myList.add("4");myList.add("5");newThread(newRunnable() {@Overridepublicvoidrun() {for(String string : myList) {System.out.println("遍历集合 value = "+ string);try{Thread.sleep(100);}catch(InterruptedException e) {e.printStackTrace();}}}}).start();newThread(newRunnable() {@Overridepublicvoidrun() {for(inti =0; i < myList.size(); i++) {String value = myList.get(i);System.out.println("删除元素 value = "+ value);if(value.equals("3")) {myList.remove(value);i--;// 注意}try{Thread.sleep(100);}catch(InterruptedException e) {e.printStackTrace();}}}}).start();</string></string>输出结果:
删除元素 value = 1
遍历集合 value = 1
删除元素 value = 2
遍历集合 value = 2
删除元素 value = 3
遍历集合 value = 3
删除元素 value = 4
遍历集合 value = 4
删除元素 value = 5
遍历集合 value = 5OK,搞定
三、参考资料
《How to Avoid ConcurrentModificationException when using an Iterator》
【转】Java ConcurrentModificationException 异常分析与解决方案--还不错的更多相关文章
- Java ConcurrentModificationException 异常分析与解决方案
Java ConcurrentModificationException 异常分析与解决方案http://www.2cto.com/kf/201403/286536.html java.util.Co ...
- 一种隐蔽性较高的Java ConcurrentModificationException异常场景
前言 在使用Iterator遍历容器类的过程中,如果对容器的内容进行增加和删除,就会出现ConcurrentModificationException异常.该异常的分析和解决方案详见博文<Jav ...
- Java ConcurrentModificationException异常原因和解决方法
Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...
- Java并发编程:Java ConcurrentModificationException异常原因和解决方法
Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...
- 【转】Java ConcurrentModificationException异常原因和解决方法
原文网址:http://www.cnblogs.com/dolphin0520/p/3933551.html Java ConcurrentModificationException异常原因和解决方法 ...
- 9、Java ConcurrentModificationException异常原因和解决方法
Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...
- java.util.ConcurrentModificationException异常分析
Java在操作ArrayList.HashMap.TreeMap等容器类时,遇到了java.util.ConcurrentModificationException异常.以ArrayList为例,如下 ...
- spark not serializable异常分析及解决方案
转载自: http://bigdataer.net/?p=569 1.背景 在使用spark开发分布式数据计算作业过程中或多或少会遇到如下的错误: Serialization stack: objec ...
- (转)Java ConcurrentModificationException异常原因和解决方法
转载自:http://www.cnblogs.com/dolphin0520/p/3933551.html 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会 ...
随机推荐
- PHP之APC缓存详细介绍
1.APC缓存简介 APC,全称是Alternative PHP Cache,官方翻译叫"可选PHP缓存".它为我们提供了缓存和优化PHP的中间代码的框架. APC的缓存分两部分: ...
- PHP 发邮件不换行
Content-Type:用于定义用户的浏览器或相关设备如何显示将要加载的数据,或者如何处理将要加载的数据 MIME:MIME类型就是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件 ...
- 在MessageBox的Show方法中如何无限使用参数值?
今天发现在show方法中不能使用花括号的方式使用多个可变参数,经过查询得出结果.在show方法中是不存在花括号的方式使用参数的.在Console.WriteLine中是存在的,如下: 那么在show方 ...
- [FTP] FTPClient--FTP操作帮助类,上传下载,文件,目录操作 (转载)
点击下载 FTPClient.zip 这个类是关于FTP客户端的操作1.构造函数 2.字段 服务器账户密码3.属性4.链接5.传输模式6.文件操作7.上传和下载8.目录操作9.内容函数看下面代码吧 / ...
- ITPub 上的一道题,学习下思路
有意思的,从别处看来的即可为己用--拿来主义 数据库:MS SQL 2000: drop table mytest go create table mytest ( sn int, ...
- Winedt 7.0 Build: 20120321 永久试用方法 WinEdt 7.0 破解
该方法,不是破解. 因为WinEdt试用版与正式版功能无异. 所以,该方法是 通过更新注册表信息,重置安装时间. 也就是重新获取31天的试用期时长. 方法如下: 1.用管理员权限打开CMD. 2.运行 ...
- tomcat gc问题总结
Java内存泄露监控工具:JVM监控工具介绍 http://developer.51cto.com/art/201203/321431.htm 关于施用full gc频繁的分析及解决 http:/ ...
- 18款js和jquery文字特效代码分享
18款js和jquery文字特效代码分享 jQCloud标签云插件_热门城市文字标签云代码 js 3d标签云特效关键词文字球状标签云代码 原生JS鼠标悬停文字球状放大显示效果代码 原生js文字动画圆形 ...
- 【转】Eclipse工具使用技巧总结
作者:Work Hard Work Smart 出处:http://www.cnblogs.com/linlf03/ 可参考http://www.codeceo.com/article/eclipse ...
- jQuery获取Select选择的Text和 Value
jQuery获取Select选择的Text和Value:语法解释:1. $("#select_id").change(function(){//code...}); //为Se ...