ArrayList在多线程时抛出ConcurrentModificationException异常的原因和解决方法

下方代码抛出java.util.ConcurrentModificationException异常

下面这段代码会报 java.util.ConcurrentModificationException 并发修改异常!

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

// java.util.ConcurrentModificationException 并发修改异常!
public class ListTest {
    public static void main(String[] args) {
        List<String> list =new ArrayList<>();

        for (int i = 1; i <= 30; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}

查找原因的方法

IDEA中打断点调试。
在PrintStream类的void println(Object x)方法的String s = String.valueOf(x);代码上打断点,调试时按Step Into。

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

异常产生的原因

把问题出现的范围缩小,即下方代码。注意:这里的list变量是ArrayList的对象。

for (int i = 1; i <= 30; i++) {
    new Thread(()->{
        list.add(UUID.randomUUID().toString().substring(0,5));
        System.out.println(list);
    },String.valueOf(i)).start();
}

创建了30个线程,每个线程都要先执行list.add(String e),然后执行System.out.println(list);。
下图展现了涉及的类和属性和方法。
在这里插入图片描述

下图展现了方法之间的调用,即每个线程依次会执行:
list.add(String e)->modCount++;->System.out.println(list);->Iterator<E> it = new Itr();->int expectedModCount = modCount;->it.next();->checkForComodification()->if (modCount != expectedModCount)throw new ConcurrentModificationException();

在这里插入图片描述
ConcurrentModificationException异常产生的原因:因为这30个线程使用的是同一个list,同一个list里有同一个modCount,但每个线程在打印list的时候,都会Iterator<E> it = new Itr();,并且int expectedModCount = modCount;,每个线程都产生一个it和其中的expectedModCount 。如果A线程已经做完了Iterator<E> it = new Itr();,和int expectedModCount = modCount;,然后时间片用完了,B线程获得了CPU,B线程执行了list.add(String e)使得modCount++;,然后,当A线程再次获得CPU的时候,B线程在打印list的过程中,执行了it.next();方法,然后进入了checkForComodification()方法,发现modCount != expectedModCount(因为modCount已经被A线程增大了),于是抛出ConcurrentModificationException

找出原因的具体步骤

list.add()

ArrayList类中的add()方法中,modCount++;

ArrayList类中的add()方法如下,注意modCount加一了。

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

这个modCount继承自AbstractList<E>类,继承来了int modCount

AbstractList类里的变量:

protected transient int modCount = 0;

ArrayList类继承AbstractList类,即继承来了int modCount 这个变量。

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
System.out.println(list);

System.out.println(list);,导致进入PrintStream类的void println(Object x)方法:

    public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

由上方代码的String.valueOf(x);进入String类的String valueOf(Object obj)方法:

    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

由上方代码的obj.toString();进入AbstractCollection类的String toString()方法:

    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

由上方代码的Iterator it = iterator();进入了ArrayList类的iterator()方法

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

由上方代码的new Itr();使得int expectedModCount = modCount;。Itr是ArrayList类的内部类。

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

返回到toString()方法。

    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }

由上方代码的E e = it.next();进入ArrayList类的内部类Itr的next()方法。

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

由上方代码的checkForComodification();进入ArrayList类的内部类Itr的checkForComodification();方法。就在这里抛出ConcurrentModificationException异常。

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

解决方法

解决方案:把 List<String> list =new ArrayList<>();改为下方三个中的一种。

  • 1、List<String> list = new Vector<>();
  • 2、List<String> list = Collections.synchronizedList(new ArrayList<>());
  • 3、List<String> list = new CopyOnWriteArrayList<>();

参考

java.util.ConcurrentModificationException异常分析及解决_学而不思则罔 思而不学则殆-CSDN博客
idea中的Diagram功能,查看类图_qq_36555038的博客-CSDN博客

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用ArrayList进行for循环,如果在循环过程中对ArrayList进行了结构性修改(比如增加或删除元素),就抛出ConcurrentModificationException异常。这个异常的出现是因为在使用迭代器进行循环,迭代器在循环开始记录ArrayList的modCount(修改次数)值,当发现在循环过程中modCount的值发生了改变,就抛出ConcurrentModificationException异常。这是一种安全机制,用于确保迭代过程中不发生数据结构的并发修改。所以,如果需要在循环过程中对ArrayList进行修改,建议使用Iterator的remove方法进行操作,而不是直接在循环内部使用ArrayList的add或remove方法。另外,如果需要在多线程环境下使用ArrayList,可以考虑使用线程安全的类,比如CopyOnWriteArrayList。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [ArrayList多线程抛出ConcurrentModificationException异常原因解决方法](https://blog.csdn.net/wpw2000/article/details/115265271)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [ArrayList什么情况抛出ConcurrentModificationException](https://blog.csdn.net/qq_34681580/article/details/110451389)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值