对JAVA集合进行遍历删除时务必要用迭代器

今天同事写了几行类似这样的代码:

package cn.iigrowing.threads.study.CollectionModify;

import java.util.ArrayList;
import java.util.List;

public class ConcurrentModificationExceptionDemo {
public static void main(String args[]) {
List<String> famous = new ArrayList<String>();
famous.add("liudehua");
famous.add("madehua");
famous.add("liushishi");
famous.add("tangwei");
for (String s : famous) {
if (s.equals("madehua")) {
famous.remove(s);
}
}
}
}

运行出异常:

Exception in thread "main" java.util.ConcurrentModificationException

at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)

at java.util.AbstractList$Itr.next(AbstractList.java:343)

at com.bes.Test.main(Test.java:15)

Java新手最容易犯的错误,对JAVA集合进行遍历删除时务必要用迭代器。切记。

其实对于如上for循环,运行过程中还是转换成了如下代码:

package cn.iigrowing.threads.study.CollectionModify;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ConcurrentModificationExceptionDemoErr2 {
public static void main(String args[]) {
List<String> famous = new ArrayList<String>();
famous.add("liudehua");
famous.add("madehua");
famous.add("liushishi");
famous.add("tangwei");
for (Iterator<String> it = famous.iterator(); it.hasNext();) {
String s = it.next();
if (s.equals("madehua")) {
famous.remove(s);
}
System.out.println(s);
}

}
}
仍然采用的是迭代器,但删除操作却用了错误的方法。如将famous.remove(s)改成it.remove()

则运行正常,结果也无误。

---

package cn.iigrowing.threads.study.CollectionModify;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ConcurrentModificationExceptionDemoOk {
public static void main(String args[]) {
List<String> famous = new ArrayList<String>();
famous.add("liudehua");
famous.add("madehua");
famous.add("liushishi");
famous.add("tangwei");

// 打印全部集合
for (Iterator<String> it = famous.iterator(); it.hasNext();) {
if (it.hasNext()) {
System.out.println(it.next());
}
}
System.out.println("---------------");

for (Iterator<String> it = famous.iterator(); it.hasNext();) {
String s = it.next();
if (s.equals("madehua")) {
it.remove();
}
}

// 打印处理完成的 情况
for (Iterator<String> it = famous.iterator(); it.hasNext();) {
if (it.hasNext()) {
System.out.println(it.next());
}
}

}
}

---

当然如果改成:

-------

package cn.iigrowing.threads.study.CollectionModify;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ConcurrentModificationExceptionDemoOk2 {
public static void main(String args[]) {
List<String> famous = new ArrayList<String>();
famous.add("liudehua");
famous.add("madehua");
famous.add("liushishi");
famous.add("tangwei");

// 打印全部集合
for (Iterator<String> it = famous.iterator(); it.hasNext();) {
if (it.hasNext()) {
System.out.println(it.next());
}
}
System.out.println("---------------");

for (int i = 0; i < famous.size(); i++) {
String s = famous.get(i);
if (s.equals("madehua")) {
famous.remove(s);
}
}

// 打印处理完成的 情况
for (Iterator<String> it = famous.iterator(); it.hasNext();) {
if (it.hasNext()) {
System.out.println(it.next());
}
}

}
}

-------
这种方法,也是可以完成功能,但一般也不这么写。

为什么用了迭代码器就不能采用famous.remove(s)操作? 这种因为ArrayList与Iterator混合使用时会导致各自的状态出现不一样,最终出现异常。

我们看一下ArrayList中的Iterator实现:
private class Itr implements Iterator<E> {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
基本上ArrayList采用size属性来维护自已的状态,而Iterator采用cursor来来维护自已的状态。

当size出现变化时,cursor并不一定能够得到同步,除非这种变化是Iterator主动导致的。

从上面的代码可以看到当Iterator.remove方法导致ArrayList列表发生变化时,他会更新cursor来同步这一变化。但其他方式导致的ArrayList变化,Iterator是无法感知的。ArrayList自然也不会主动通知Iterator们,那将是一个繁重的工作。Iterator到底还是做了努力:为了防止状态不一致可能引发的无法设想的后果,Iterator会经常做checkForComodification检查,以防有变。如果有变,则以异常抛出,所以就出现了上面的异常。

如果对正在被迭代的集合进行结构上的改变(即对该集合使用add、remove或clear方法),那么迭代器就不再合法(并且在其后使用该迭代器将会有ConcurrentModificationException异常被抛出).

如果使用迭代器自己的remove方法,那么这个迭代器就仍然是合法的。

package chapter1;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
* Created by MyWorld on 2016/3/3.
*/
public class FastFailResolver {

public static void main(String[] args) {
Map<String, String> source = new HashMap<String, String>();
for (int i = 0; i < 10; i++) {
source.put("key" + i, "value" + i);
}
System.out.println("Source:" + source);
// fastFailSceneWhenRemove(source);
commonSceneWhenRemove(source);

}

private static void commonSceneWhenRemove(Map<String, String> source) {
Iterator<Map.Entry<String, String>> iterator = source.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
if (entry.getKey().contains("1")) {
iterator.remove();
}
}
System.out.println(source);
}

private static void fastFailSceneWhenRemove(Map<String, String> source) {
for (Map.Entry<String, String> entry : source.entrySet()) {
if (entry.getKey().contains("1")) {
source.remove(entry.getKey());
}
}
System.out.println(source);
}
}

3.在一个循环中删除一个列表中的元素
思考下面这一段在循环中删除多个元素的的代码

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
for(int i=0;i<list.size();i++){
list.remove(i);
}
System.out.println(list);
输出结果是:

1
[b,d]
在这个方法中有一个严重的错误。当一个元素被删除时,列表的大小缩小并且下标变化,所以当你想要在一个循环中用下标删除多个元素的时候,它并不会正常的生效。

与下面结合的一个示例:

public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","a", "b",
"c", "d"));
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals("a")) {
list.remove(i);
}
}
System.out.println(list);
}

输出:

[a, b, c, d]
即输出与预期不一致
你也许知道在循环中正确的删除多个元素的方法是使用迭代,并且你知道java中的foreach循环看起来像一个迭代器,但实际上并不是。考虑一下下面的代码:

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
for(String s:list){
if(s.equals("a")){
list.remove(s);
}
}
它会抛出一个ConcurrentModificationException异常。 相反下面的显示正常:

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
String s = iter.next();
if(s.equals("a")){
iter.remove();
}
}
.next()必须在.remove()之前调用。在一个foreach循环中,编译器会使.next()在删除元素之后被调用,因此就会抛出ConcurrentModificationException异常,你也许希望看一下ArrayList.iterator()的源代码。

http://www.cnblogs.com/softidea/p/4279574.html

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorTest{
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
list.add("Test4");
list.add("Test5");

for(Iterator<String> it = list.iterator();it.hasNext();){
if(it.next().equals("Test3")){
it.remove();
}
}

for(String s : list){
System.out.println(s);
}

}
}

Iterator 支持从源集合中安全地删除对象,只需在 Iterator 上调用 remove() 即可。这样做的好处是可以避免 ConcurrentModifiedException ,这个异常顾名思意:当打开 Iterator 迭代集合时,同时又在对集合进行修改。
有些集合不允许在迭代时删除或添加元素,但是调用 Iterator 的remove() 方法是个安全的做法。

java.util.ConcurrentModificationException详解

http://blog.csdn.net/smcwwh/article/details/7036663

【引言】
经常在迭代集合元素时,会想对集合做修改(add/remove)操作,类似下面这段代码:

for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
Integer val = it.next();
if (val == 5) {
list.remove(val);
}
}

运行这段代码,会抛出异常java.util.ConcurrentModificationException。

【解惑】

(以ArrayList来讲解)在ArrayList中,它的修改操作(add/remove)都会对modCount这个字段+1,modCount可以看作一个版本号,每次集合中的元素被修改后,都会+1(即使溢出)。接下来再看看AbsrtactList中iteraor方法

public Iterator<E> iterator() {
return new Itr();
}

它返回一个内部类,这个类实现了iterator接口,代码如下:
private class Itr implements Iterator<E> {
int cursor = 0;

int lastRet = -1;

int expectedModCount = modCount;

public boolean hasNext() {
return cursor != size();
}

public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}

public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();

try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
// 修改expectedModCount 的值
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

在内部类Itr中,有一个字段expectedModCount ,初始化时等于modCount,即当我们调用list.iterator()返回迭代器时,该字段被初始化为等于modCount。在类Itr中next/remove方法都有调用checkForComodification()方法,在该方法中检测modCount == expectedModCount,如果不相当则抛出异常ConcurrentModificationException。

前面说过,在集合的修改操作(add/remove)中,都对modCount进行了+1。
在看看刚开始提出的那段代码,在迭代过程中,执行list.remove(val),使得modCount+1,当下一次循环时,执行 it.next(),checkForComodification方法发现modCount != expectedModCount,则抛出异常。

【解决办法】
如果想要在迭代的过程中,执行删除元素操作怎么办?
再来看看内部类Itr的remove()方法,在删除元素后,有这么一句expectedModCount = modCount,同步修改expectedModCount 的值。所以,如果需要在使用迭代器迭代时,删除元素,可以使用迭代器提供的remove方法。对于add操作,则在整个迭代器迭代过程中是不允许的。 其他集合(Map/Set)使用迭代器迭代也是一样。

当使用 fail-fast iterator 对 Collection 或 Map 进行迭代操作过程中尝试直接修改 Collection / Map 的内容时,即使是在单线程下运行, java.util.ConcurrentModificationException 异常也将被抛出。
Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。
Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。

所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。
但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。

有意思的是如果你的 Collection / Map 对象实际只有一个元素的时候, ConcurrentModificationException 异常并不会被抛出。这也就是为什么在 javadoc 里面指出: it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.

 

来源: https://www.cnblogs.com/goody9807/p/6432904.html

-------------

Java集合迭代时修改

本文主要分如下几个要点:

0)Java集合分类

1)对于熟悉JDK集合源码的帮你加深对ConcurrentModificationException的下印象

2)对于迭代时修改提供一个正确的姿势。

3)单线程和多线程环境下迭代时修改的方案

PS:本文不会详细讲解每个集合的源码,也不会画出集合的继承关系(网上有太多详细的讲解和关系图)我们从另一个角度来看下集合,看你是否真正理解集合(容器)。

集合(也叫容器)归类

  1. 普通容器: List/Set/Map
  2. 同步容器:Vector/HashTable
  3. 并发容器:CopyOnWriteArrayList、ConcurrentHashMap、ArrayBlockQueue

java多线程与集合以及与你的应用程序的性能有着千丝万缕的关系。

什么是集合?

对java而言就是对一些数据结构如:数组、链表、队列、栈、以及KV对, 进行增、删、改、查、统计的内存操作,
我们都知道在内存中操作要比查询数据库写文件性能高得多,集合就是装你要做操数据的内存容器。

集合在框架中使用一定要谨慎,我们的应用大部分都是基于Spring的,那么你的Controller也基本都是单例的,如果你在Controller中有个成员是集合,你的浏览器(本质是SocketClient)每次请求到你Contorller(web容器如tomtcat接收到请求后分配一个线程来调用你的Servlet,你的应用如果是SpringMvc的话DispatchServert会将请求Mapping到你的Contorller上),这样就成了多个线程操作同一个集合了。

我们以List来举例说明下这几类结合的差别:

数组:有序可放入重复元素的同类型连续的内存区域。

几乎没什么方法,只有几个属性,你可以想象下如果在特定位置删除或者添加一个元素?

以添加的为例:
检查数组是否是满了
1)满了:换个大点的,特定位置的元素和原先老数组的全都放入到这个大的数组,
2)未满:这个位置的元素之后的每个都往后移动一下,将新的元素插入进来。
总之写代码的话就是一大坨,重复性的

List就是就是为了解决这个数组没有方法的问题的,提供add、remove、迭代、统计
我们以迭代时修改为例对比下这几类集合。

单线程环境迭代修改

最原始的迭代删除方式:

单线程环境下都不能完美正常运行,最明显的问题就是连续的集合值是符合条件的就少删除,原因就是List中的数组的下标变化了【我用的是list1.size()方法】。解决方法也就显而易见了:

删除的时候将下标减去1,保持下标是下一个真正要迭代的元素。

正确的姿势:

ps增强的for底层是Iterator,把for循环迭代看做是迭代iterator就行

前面说过for和iterator迭代的方式是一样的。可以看出我们这里只是用iterator.remove和list.remove不同而已。
抛出的异常就是ConcurrentModificationException,看下它是怎么出来的这个异常。


只要expectedModeCount!=modCount就会抛出异常

每次迭代 即便是增强的for都会new Itr 所以这个expectedModeCount=modCount

在看下这个modCount是怎么回事

就是一个ArrayList的成员,什么时候modCount的值会变化,add和remove方法都modCount++ 也就是容器被修改的时候会调用导致这个值发生变化,也就是说在迭代的过程中如果有容器被修改就会抛出这个异常。

用增强的for或者迭代器本身迭代的时候如果不是调用迭代器自身的remove方法,而是调用了list自身的方法的时候就会抛出ConcurrentModificationException异常。说到这这里单线程环境下调用使用迭代就完了。

多线程环境迭代修改

3个方法

updateRef在修改集合中的应用,并没有调用list的能使得mountCount值发生变化的

public class ListModifyGo {

    static List<User> list1 = null;
    static {
        list1 = new ArrayList<User>();
        list1.add(new User(0, "王五"));
        list1.add(new User(1, "张三"));
        list1.add(new User(2, "张三"));
        list1.add(new User(3, "李四"));
    }
//迭代结合
    void list() {
        for (User user : list1) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(user.getName());
        }
    }
//使用集合方法删除某个元素,目的是引起mountCount++
    void update() {
        list1.remove(2);
    }
//不用引起mountCount++
    void updateRef() {
        User user = list1.get(3);
        user.setName(user.getName() + " update");
    }

    public static void main(String[] args) throws Exception {
        ListModifyGo listModifyGo = new ListModifyGo();

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ",listModifyGo.list();");
                listModifyGo.list();
            }
        }, "t1").start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ",listModifyGo.update();");
                listModifyGo.update();
            }
        }, "t2").start();
    }

}

这个类很简单就是模拟两个线程一个操作同一个对象static List< User > list1
一个线程在调用list一个在调用update 本来两个方法互不干扰,但是在多线程环境下还是出现了我们不希望看到的ConcurrentModificationException异常,当然你可以在每个方法上加上synchronize,但这是你用容器的本质(提升访问速度),这样一来成了排队了违反了你使用容器的本质(性能降低了)。

有人就可能说把List换成线程安全的Vector。答案其实是否定的

public class VectorModifyGo {

    static Vector<User> vector = null;
    static {
        vector = new Vector<User>();
        vector.add(new User(0, "王五"));
        vector.add(new User(1, "张三"));
        vector.add(new User(2, "张三"));
        vector.add(new User(3, "李四"));
    }

    // synchronized 将list()变成是原子操作
    void list() {
        for (User user : vector) {// next方法被多次调用,list()是复合操作
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(user.getName());
        }
    }

    void update() {
        vector.remove(2);
    }

    void updateRef() {
        User user = vector.get(3);
        user.setName(user.getName() + " update");
    }

    public static void main(String[] args) throws Exception {
        VectorModifyGo vectorModifyGo = new VectorModifyGo();

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ",vectorModifyGo.list();");
                vectorModifyGo.list();
            }
        }, "t1").start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ",vectorModifyGo.update();");
                vectorModifyGo.update();
            }
        }, "t2").start();
    }

}

我自己试过,也会看了下Vector源码,只是在Vector相应的读写方法上加上了synchronized关键字,所有的线程走在抢占Vectory对象的锁this 但是他不能坚决此类问题,它可以解决诸如线程1在统计时候线程2不能修改(add、remove、某个下标的对象里的值都不能修改)能做到互斥。

我说下这里为什么不能,并且这个异常是随机出现的
这里写图片描述
这里写图片描述

for迭代的时候也就是new Itr()这个步骤是互斥了将modeCount赋值成了初始值,但是new完之后退出了方法体没有synchronized保护了,这个时候有可能线程2获取锁执行了remove方法modeCount++了,再迭代next方法此时就有问题。
如果线程2在remove抢占锁失败即被迭代时每次next都能成功获取锁,这个时候就不会出现异常,这要是这个异常出现的偶然性。

这种场景是典型的复合操作,多个加锁的方法被同一个方法,方法体内还是暴露了共享对象,这样在多线程环境下还是有问题的。

解决方案1:
在类的list方法上在加上synchronized让所有的next方法都在外层的然而这样锁上锁会损失性能。

解决方案2:
使用java.util.concurrent并发包下的并发容器 注入CopyOnWriteArrayList
原理就是当线程1在迭代的时候迭代的当前数组
线程2修改的时候将当前数组拷贝一份进行迭代,然后将拷贝和修改之后的数组赋值给当前数组
所以线程1迭代的时候老的数据,有些人可能不明白为什么线程1迭代的时老的数据一张图解析下:

再多说一嘴,CopyOnWriteArrayList的成员array是被volatile修饰的线程2将引用赋值之后其他线程拷贝了应用之后都能感知到array的变化。但是由于线程1执行的list已经在使用原始array了,能感知到也没有用了,而其他线程3如果刚进入方法执行list此时在如果还没有使用这块原始区域则还会重新从主存load即拷贝过后的array,这块其实是java内存模型的之后可以关注下volatile的内存原语。

这种并发容器虽然能解决多线程环境操作同一个集合的情况,但是拷贝一份的代价其实也是很大的,所以更加适用于读多写少的场景。

顺便贴一下代码修改的时候能够看到是赋值了一份:

可以看到CopyOnWriteArrayList在执行修改数组的时候拷贝了一份并且加锁了,我上图中没有表示出线程2
在修改时候是独占的,这里补充下。

来源:https://blog.csdn.net/mayongzhan_csdn/article/details/79309722