public class Test { public static void main(String[] args) { List<Integer> listA=new ArrayList<>(); listA.add(1); listA.add(2); listA.add(3); listA.add(4); listA.add(5); listA.add(6); for(Integer a:listA){ System.out.println(a); if (a==5) { listA.remove(5); } } } }
上述代码加了打印后,输出 1,2,3,4,5; 进一步证明最后一个元素6并没有被遍历到。
解决方法1
从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)方法就可以了。
解决方法2
在找到原因后,则进一步进行解决
经过查阅源码可以发现,iterator也有一个remove方法如下,其中有一个重要的操作为expectedModCount = modCount;这样就保证了两者的相等。
public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } }
修改后的代码如下:
public class Test { public static void main(String[] args) { List<Integer> listA=new ArrayList<>(); listA.add(1); listA.add(2); listA.add(3); listA.add(4); listA.add(5); listA.add(6); Iterator<Integer> it_b=listA.iterator(); while(it_b.hasNext()){ Integer a=it_b.next(); if (a==4) { it_b.remove(); } } for(Integer b:listA){ System.out.println(b); } } }
- java.util.ConcurrentModificationException异常完美解决。