GVKun编程网logo

遍历集合,在循环中删除对象时避免 ConcurrentModificationException(遍历集合时删除元素)

22

如果您对遍历集合,在循环中删除对象时避免ConcurrentModificationException和遍历集合时删除元素感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解遍历集合,在循环中删除对

如果您对遍历集合,在循环中删除对象时避免 ConcurrentModificationException遍历集合时删除元素感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解遍历集合,在循环中删除对象时避免 ConcurrentModificationException的各种细节,并对遍历集合时删除元素进行深入的分析,此外还有关于- 集合 遍历 foreach Iterator 并发修改 ConcurrentModificationException MD、ArrayList中foreach循环中增添、删除导致ConcurrentModificationException、ConcurrentModificationException、ConcurrentModificationException 源码解析的实用技巧。

本文目录一览:

遍历集合,在循环中删除对象时避免 ConcurrentModificationException(遍历集合时删除元素)

遍历集合,在循环中删除对象时避免 ConcurrentModificationException(遍历集合时删除元素)

我们都知道您不能执行以下操作,因为ConcurrentModificationException

for (Object i : l) {
    if (condition(i)) {
        l.remove(i);
    }
}

但这显然有时有效,但并非总是如此。下面是一些具体的代码:

public static void main(String[] args) {
    Collection<Integer> l = new ArrayList<>();

    for (int i = 0; i < 10; ++i) {
        l.add(4);
        l.add(5);
        l.add(6);
    }

    for (int i : l) {
        if (i == 5) {
            l.remove(i);
        }
    }

    System.out.println(l);
}

当然,这会导致:

Exception in thread "main" java.util.ConcurrentModificationException

即使多个线程没有这样做。反正。

这个问题的最佳解决方案是什么?如何在不引发此异常的情况下循环从集合中删除项目?

我在Collection这里也使用了任意的,不一定是ArrayList,所以你不能依赖get.

- 集合 遍历 foreach Iterator 并发修改 ConcurrentModificationException MD

- 集合 遍历 foreach Iterator 并发修改 ConcurrentModificationException MD

Markdown 版本笔记 我的 GitHub 首页 我的博客 我的微信 我的邮箱
MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina.com

目录

[TOC]

为什么不能在 foreach 循环里进行元素的 remove/add 操作

参考: Hollis 的公众号文章

背景

在阿里巴巴 Java 开发手册中,有这样一条规定:

但是手册中并没有给出具体原因,本文就来深入分析一下该规定背后的思考。

foreach 循环

foreach 循环(Foreach loop)是计算机编程语言中的一种控制流程语句,通常用来循环遍历数组或集合中的元素。

Java 语言从 JDK 1.5.0 开始引入 foreach 循环。在遍历数组、集合方面,foreach 为开发人员提供了极大的方便。通常也被称之为增强for循环

foreach 语法格式如下:

for(元素类型t 元素变量x : 遍历对象obj){ 
     引用了xjava语句; 
}

以下实例演示了 普通 for 循环 和 foreach 循环使用:

public static void main(String[] args) {
    // 使用ImmutableList初始化一个List
    List<String> userNames = ImmutableList.of("Hollis", "hollis", "HollisChuang", "H");

    System.out.println("使用for循环遍历List");
    for (int i = 0; i < userNames.size(); i++) {
        System.out.println(userNames.get(i));
    }

    System.out.println("使用foreach遍历List");
    for (String userName : userNames) {
        System.out.println(userName);
    }
}

可以看到,使用 foreach 语法遍历集合或者数组的时候,可以起到和普通 for 循环同样的效果,并且代码更加简洁。所以,foreach 循环也通常也被称为增强 for 循环。

但是,作为一个合格的程序员,我们不仅要知道什么是增强 for 循环,还需要知道增强for循环的原理是什么

其实,增强 for 循环也是 Java 给我们提供的一个语法糖,如果将以上代码编译后的 class 文件进行反编译(使用 jad 工具)的话,可以得到以下代码:

Iterator iterator = userNames.iterator();
do{
    if(!iterator.hasNext())
        break;
    String userName = (String)iterator.next();
    if(userName.equals("Hollis"))
        userNames.remove(userName);
} while(true);
System.out.println(userNames);

可以发现,原本的增强 for 循环,其实是依赖了 while 循环和 Iterator 实现的。

问题重现

规范中指出不让我们在 foreach 循环中对集合元素做 add/remove 操作,那么,我们尝试着做一下看看会发生什么问题。

首先使用双括弧语法(double-brace syntax)建立并初始化一个 List,其中包含四个字符串,分别是 Hollis、hollis、HollisChuang 和 H:

List<String> userNames = new ArrayList<String>() {{
    add("Hollis");
    add("hollis");
    add("HollisChuang");
    add("H");
}};

然后使用普通 for 循环对 List 进行遍历,删除 List 中元素内容等于 Hollis 的元素,然后输出 List:

for (int i = 0; i < userNames.size(); i++) {
    if (userNames.get(i).equals("Hollis")) {
        userNames.remove(i);
    }
}
System.out.println(userNames);

输出结果如下

[hollis, HollisChuang, H]

以上是使用普通的 for 循环在遍历的同时进行删除,那么,我们再看下,如果使用增强 for 循环的话会发生什么:

for (String userName : userNames) {
    if (userName.equals("Hollis")) {
        userNames.remove(userName);
    }
}
System.out.println(userNames);

以上代码,使用增强 for 循环遍历元素,并尝试删除其中的 Hollis 字符串元素。运行以上代码,会抛出以下异常:

java.util.ConcurrentModificationException

同样的,读者可以尝试下在增强 for 循环中使用 add 方法添加元素,结果也会同样抛出该异常。

之所以会出现这个异常,是因为触发了一个 Java 集合的错误检测机制 ——fail-fast

fail-fast

接下来,我们就来分析下在增强 for 循环中 add/remove 元素的时候会抛出 java.util.ConcurrentModificationException 的原因,即解释下到底什么是 fail-fast 进制。

fail-fast,即快速失败,它是 Java 集合的一种错误检测机制当多个线程对非fail-safe的集合类进行结构上的改变的操作时,有可能会产生fail-fast机制,这个时候就会抛出 ConcurrentModificationException(当方法检测到对象的并发修改,但不允许这种修改时就抛出该异常)。

需要注意的是,即使不是多线程环境,如果单线程违反了规则,同样也有可能会抛出改异常。

那么,在增强 for 循环进行元素删除,是如何违反了规则的呢?

要分析这个问题,我们先将增强 for 循环这个语法糖进行解糖(使用 jad 对编译后的 class 文件进行反编译),得到以下代码:

public static void main(String[] args) {
    // 使用ImmutableList初始化一个List
    List<String> userNames = new ArrayList<String>() {{
        add("Hollis");
        add("hollis");
        add("HollisChuang");
        add("H");
    }};

    Iterator iterator = userNames.iterator();
    do
    {
        if(!iterator.hasNext())
            break;
        String userName = (String)iterator.next();
        if(userName.equals("Hollis"))
            userNames.remove(userName);
    } while(true);
    System.out.println(userNames);
}

然后运行以上代码,同样会抛出异常。我们来看一下 ConcurrentModificationException 的完整堆栈:

通过异常堆栈我们可以到,异常发生的调用链 ForEachDemo 的第 23 行,Iterator.next 调用了 Iterator.checkForComodification 方法 ,而异常就是 checkForComodification 方法中抛出的。

其实,经过 debug 后,我们可以发现,如果 remove 代码没有被执行过,iterator.next 这一行是一直没报错的。抛异常的时机也正是 remove执行之后的的那一次next方法的调用

我们直接看下 checkForComodification 方法的代码,看下抛出异常的原因:

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

代码比较简单,modCount != expectedModCount 的时候,就会抛出 ConcurrentModificationException。

那么,就来看一下,remove/add 操作室如何导致 modCount 和 expectedModCount 不相等的吧。

remove/add 做了什么

首先,我们要搞清楚的是,到底 modCount 和 expectedModCount 这两个变量都是个什么东西。

通过翻源码,我们可以发现:

  • modCount 是 ArrayList 中的一个成员变量。它表示该集合实际被修改的次数。
  • expectedModCount 是 ArrayList 中的一个内部类 ——Itr 中的成员变量。expectedModCount 表示这个迭代器期望该集合被修改的次数。其值是在 ArrayList.iterator 方法被调用的时候初始化的。只有通过迭代器对集合进行操作,该值才会改变。

Itr 是一个 Iterator 的实现,使用 ArrayList.iterator 方法可以获取到的迭代器就是 Itr 类的实例。

他们之间的关系如下:

class ArrayList{
    private int modCount;
    public void add();
    public void remove();
    private class Itr implements Iterator<E> {
        int expectedModCount = modCount;
    }
    public Iterator<E> iterator() {
        return new Itr();
    }
}

其实,看到这里,大概很多人都能猜到为什么 remove/add 操作之后,会导致 expectedModCount 和 modCount 不想等了。

通过翻阅代码,我们也可以发现,remove 方法核心逻辑如下: !

可以看到,它只修改了 modCount,并没有对 expectedModCount 做任何操作。

简单总结一下,之所以会抛出 ConcurrentModificationException 异常,是因为我们的代码中使用了增强 for 循环,而在增强for循环中,集合遍历是通过iterator进行的,但是元素的add/remove却是直接使用的集合类自己的方法。这就导致 iterator 在遍历的时候,会发现有一个元素在自己不知不觉的情况下就被删除 / 添加了,就会抛出一个异常,用来提示用户,可能发生了并发修改

正确姿势

至此,我们介绍清楚了不能在 foreach 循环体中直接对集合进行 add/remove 操作的原因。

但是,很多时候,我们是有需求需要过滤集合的,比如删除其中一部分元素,那么应该如何做呢?有几种方法可供参考:

直接使用普通 for 循环进行操作

我们说不能在 foreach 中进行,但是使用普通的 for 循环还是可以的,因为普通 for 循环并没有用到 Iterator 的遍历,所以压根就没有进行 fail-fast 的检验。

for (int i = 0; i < 1; i++) {
    if (userNames.get(i).equals("Hollis")) {
        userNames.remove(i);
    }
}

直接使用 Iterator 进行操作

除了直接使用普通 for 循环以外,我们还可以直接使用 Iterator 提供的 remove 方法。

Iterator iterator = userNames.iterator();
while (iterator.hasNext()) {
    if (iterator.next().equals("Hollis")) {
        iterator.remove();
    }
}

如果直接使用 Iterator 提供的 remove 方法,那么就可以修改到 expectedModCount 的值。那么就不会再抛出异常了。其实现代码如下:

使用 Java8 中提供的 filter 过滤

Java 8 中可以把集合转换成流,对于流有一种 filter 操作, 可以对原始 Stream 进行某项测试,通过测试的元素被留下来生成一个新 Stream。

userNames = userNames.stream()
    .filter(userName -> !userName.equals("Hollis"))
    .collect(Collectors.toList());

使用 fail-safe 的集合类

在 Java 中,除了一些普通的集合类以外,还有一些采用了 fail-safe 机制的集合类,比如 ConcurrentLinkedDeque。这样的集合容器在遍历时不是直接在集合内容上访问的,而是先复制原有集合内容,在拷贝的集合上进行遍历

由于迭代时是对原集合的拷贝进行遍历,所以在遍历过程中对原集合所作的修改并不能被迭代器检测到,所以不会触发 ConcurrentModificationException。

基于拷贝内容的优点是避免了 ConcurrentModificationException,但同样地,迭代器并不能访问到修改后的内容,即:迭代器遍历的是开始遍历那一刻拿到的集合拷贝,在遍历期间原集合发生的修改迭代器是不知道的。

java.util.concurrent 包下的容器都是安全失败,可以在多线程下并发使用,并发修改。

使用增强 for 循环其实也可以

如果,我们非常确定在一个集合中,某个即将删除的元素只包含一个的话, 比如对 Set 进行操作,那么其实也是可以使用增强 for 循环的,只要在删除之后,立刻结束循环体,不要再继续进行遍历就可以了,也就是说不让代码执行到下一次的next方法

for (String userName : userNames) {
    if (userName.equals("Hollis")) {
        userNames.remove(userName);
        break;
    }
}

以上这五种方式都可以避免触发 fail-fast 机制,避免抛出异常。如果是并发场景,建议使用 concurrent 包中的容器,如果是单线程场景,Java8 之前的代码中,建议使用 Iterator 进行元素删除,Java8 及更新的版本中,可以考虑使用 Stream 及 filter。

总结

我们使用的增强 for 循环,其实是 Java 提供的语法糖,其实现原理是借助 Iterator 进行元素的遍历。

但是如果在遍历过程中,不通过 Iterator,而是通过集合类自身的方法对集合进行添加 / 删除操作。那么在 Iterator 进行下一次的遍历时,经检测发现有一次集合的修改操作并未通过自身进行,那么可能是发生了并发被其他线程执行的,这时候就会抛出异常,来提示用户可能发生了并发修改,这就是所谓的 fail-fast 机制。

当然还是有很多种方法可以解决这类问题的。比如使用普通 for 循环、使用 Iterator 进行元素删除、使用 Stream 的 filter、使用 fail-safe 的类等。

ArrayList中foreach循环中增添、删除导致ConcurrentModificationException

ArrayList中foreach循环中增添、删除导致ConcurrentModificationException

一、使用背景

在阿里巴巴开发手册中,有这样一条规定:不要在foreach循环里进行add和remove操作(这里指的是List的add和remove操作),否则会抛出ConcurrentModificationException。remove元素请使用iterator。

f29f0bec6c933e9d6fb3fb414219ef4.png

二、源码

1.我们知道foreach是语法糖,他本质还是iterator进行的循环,因此下面的代码和使用foreach循环是一样的。在循环里面我们使用“错误”操作,使用List的add方法进行操作,会抛出ConcurrentModificationException

       ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("apple");
        Iterator<String> iterator = arrayList.iterator();
        while(iterator.hasNext()){
            String value = iterator.next();
            if("apple".equals(value)){
                arrayList.add("orange");
            }
        }

三、源码解析

1.arrayList.iterator();

①返回Itr类,并将modcount的值赋值给一个变量expectedModCount,其中modcount表示List实际被增删的次数,expectedModCount表示该迭代器期望被增删的次数,当新建Itr类的时候会给他赋初始值,只有通过该迭代器进行值的增删才会修改该值

1f94f5447debd05c92a2ce77cf2bf53.png

0f9094193aa7672ddd5392485494233.png

2.iterator.next();

①在调用迭代器的next方法时,他会进行检查,比较modCount和expectedModCount的值,如果不相等,Concurrent

a06c77dae6f16bf2838a90466954f5c.png

05b5c8ca957494affd4157961ac3763.png

四、总结

1.modCount和expectedModeCount不一致才会抛出ConcurrentModificationException。当我们调用List的remove方法时,他只会修改modCount的值;当我们调用iterator的remove方法,他会将modCount的值赋值给expectedModeCount

2.modCount和expectedModeCount是属于fast-fail机制,用于多线程中,当进行遍历的时候,有其他线程修改值的时候就会进行检查

五、解决方法

1.使用普通for循环进行操作

2.在循环中使用iterator进行操作

3.使用stream流进行过滤

4.使用fast-saft安全的类,如ConCurrentLinkedQueue

ConcurrentModificationException

ConcurrentModificationException

ConcurrentModificationException

    虽然类似Vector这种线程安全的容器,还是会发生不安全行为。当Vector在迭代的时候(iteretor),其他的线程并发的去修改这个容器的时候,会触发ConcurrentModificationException。因为当初设计迭代器的时候,并没有考虑到并发修改的问题,因此在迭代的时候,需要加锁。

ConcurrentModificationException 源码解析

ConcurrentModificationException 源码解析

ConcurrentModificationException 源码解析 博客分类: java
// Iterators

    /**
     * Returns an iterator over the elements in this list in proper
     * sequence. <p>
     *
     * This implementation returns a straightforward implementation of the
     * iterator interface, relying on the backing list''s <tt>size()</tt>,
     * <tt>get(int)</tt>, and <tt>remove(int)</tt> methods.<p>
     *
     * Note that the iterator returned by this method will throw an
     * <tt>UnsupportedOperationException</tt> in response to its
     * <tt>remove</tt> method unless the list''s <tt>remove(int)</tt> method is
     * overridden.<p>
     *
     * This implementation can be made to throw runtime exceptions in the face
     * of concurrent modification, as described in the specification for the
     * (protected) <tt>modCount</tt> field.
     *
     * @return an iterator over the elements in this list in proper sequence.
     * 
     * @see #modCount
     */
    public Iterator<E> iterator() {
	return new Itr();
    }

   

   

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.
         *这个modCount值,迭代器相信支持列表应该有。如果这种期望是违反,迭代器已检测到并发改          *。就会报异常
	 */
	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();
	    }
	}

 

  

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

 

关于遍历集合,在循环中删除对象时避免 ConcurrentModificationException遍历集合时删除元素的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于- 集合 遍历 foreach Iterator 并发修改 ConcurrentModificationException MD、ArrayList中foreach循环中增添、删除导致ConcurrentModificationException、ConcurrentModificationException、ConcurrentModificationException 源码解析等相关内容,可以在本站寻找。

本文标签: