Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 510|回复: 0

[默认分类] Java ConcurrentModificationException异常原因和解决方法

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2020-8-16 16:36:38 | 显示全部楼层 |阅读模式
    java ConcurrentModificationException异常原因和解决方法
      在前面一篇文章中提到,对Vector、ArrayList在迭代的时候如果同时对其进行修改就会抛出java.util.ConcurrentModificationException异常。下面我们就来讨论以下这个异常出现的原因以及解决办法。
      以下是本文目录大纲:
      一.ConcurrentModificationException异常出现的原因
      二.在单线程环境下的解决办法
      三.在多线程环境下的解决方法
      若有不正之处请多多谅解,并欢迎批评指正
      请尊重作者劳动成果,转载请标明原文链接:
      http://www.cnblogs.com/dolphin0520/p/3933551.HTML
    一.ConcurrentModificationException异常出现的原因
      先看下面这段代码:

    1. public class Test {
    2.         public static void main(String[] args)  {
    3.                 ArrayList<Integer> list = new ArrayList<Integer>();
    4.                 list.add(2);
    5.                 Iterator<Integer> iterator = list.iterator();
    6.                 while(iterator.hasNext()){
    7.                         Integer integer = iterator.next();
    8.                         if(integer==2)
    9.                                 list.remove(integer);
    10.                 }
    11.         }
    12. }
    复制代码


      运行结果:
      
      从异常信息可以发现,异常出现在checkForComodification()方法中。
      我们不忙看checkForComodification()方法的具体实现,我们先根据程序的代码一步一步看ArrayList源码的实现:
      首先看ArrayList的iterator()方法的具体实现,查看源码发现在ArrayList的源码中并没有iterator()这个方法,那么很显然这个方法应该是其父类或者实现的接口中的方法,我们在其父类AbstractList中找到了iterator()方法的具体实现,下面是其实现代码:

    1. public Iterator<E> iterator() {
    2.         return new Itr();
    3. }
    复制代码


      从这段代码可以看出返回的是一个指向Itr类型对象的引用,我们接着看Itr的具体实现,在AbstractList类中找到了Itr类的具体实现,它是AbstractList的一个成员内部类,下面这段代码是Itr类的所有实现:

    1. private class Itr implements Iterator<E> {
    2.         int cursor = 0;
    3.         int lastRet = -1;
    4.         int expectedModCount = modCount;
    5.         public boolean hasNext() {
    6.            return cursor != size();
    7.         }
    8.         public E next() {
    9.            checkForComodification();
    10.             try {
    11.                 E next = get(cursor);
    12.                 lastRet = cursor++;
    13.                 return next;
    14.             } catch (IndexOutOfBoundsException e) {
    15.                 checkForComodification();
    16.                 throw new NoSuchElementException();
    17.             }
    18.         }
    19.         public void remove() {
    20.             if (lastRet == -1)
    21.                 throw new IllegalStateException();
    22.            checkForComodification();
    23.             try {
    24.                 AbstractList.this.remove(lastRet);
    25.                 if (lastRet < cursor)
    26.                     cursor--;
    27.                 lastRet = -1;
    28.                 expectedModCount = modCount;
    29.             } catch (IndexOutOfBoundsException e) {
    30.                 throw new ConcurrentModificationException();
    31.             }
    32.         }
    33.         final void checkForComodification() {
    34.             if (modCount != expectedModCount)
    35.                 throw new ConcurrentModificationException();
    36.         }
    37. }
    复制代码


      首先我们看一下它的几个成员变量:
      cursor:表示下一个要访问的元素的索引,从next()方法的具体实现就可看出
      lastRet:表示上一个访问的元素的索引
      expectedModCount:表示对ArrayList修改次数的期望值,它的初始值为modCount。
      modCount是AbstractList类中的一个成员变量

    1. protected transient int modCount = 0;
    复制代码


      该值表示对List的修改次数,查看ArrayList的add()和remove()方法就可以发现,每次调用add()方法或者remove()方法就会对modCount进行加1操作。
      好了,到这里我们再看看上面的程序:
      当调用list.iterator()返回一个Iterator之后,通过Iterator的hashNext()方法判断是否还有元素未被访问,我们看一下hasNext()方法,hashNext()方法的实现很简单:

    1. public boolean hasNext() {
    2.     return cursor != size();
    3. }
    复制代码


      如果下一个访问的元素下标不等于ArrayList的大小,就表示有元素需要访问,这个很容易理解,如果下一个访问元素的下标等于ArrayList的大小,则肯定到达末尾了。
      然后通过Iterator的next()方法获取到下标为0的元素,我们看一下next()方法的具体实现:

    1. public E next() {
    2.     checkForComodification();
    3. try {
    4.         E next = get(cursor);
    5.         lastRet = cursor++;
    6.         return next;
    7. } catch (IndexOutOfBoundsException e) {
    8.         checkForComodification();
    9.         throw new NoSuchElementException();
    10. }
    11. }
    复制代码


      这里是非常关键的地方:首先在next()方法中会调用checkForComodification()方法,然后根据cursor的值获取到元素,接着将cursor的值赋给lastRet,并对cursor的值进行加1操作。初始时,cursor为0,lastRet为-1,那么调用一次之后,cursor的值为1,lastRet的值为0。注意此时,modCount为0,expectedModCount也为0。
      接着往下看,程序中判断当前元素的值是否为2,若为2,则调用list.remove()方法来删除该元素。
      我们看一下在ArrayList中的remove()方法做了什么:

    1. public boolean remove(Object o) {
    2.         if (o == null) {
    3.                 for (int index = 0; index < size; index++)
    4.                         if (elementData[index] == null) {
    5.                                 fastRemove(index);
    6.                                 return true;
    7.                         }
    8.         } else {
    9.                 for (int index = 0; index < size; index++)
    10.                         if (o.equals(elementData[index])) {
    11.                                 fastRemove(index);
    12.                                 return true;
    13.                         }
    14.         }
    15.         return false;
    16. }
    17. private void fastRemove(int index) {
    18.         modCount++;
    19.         int numMoved = size - index - 1;
    20.         if (numMoved > 0)
    21.                 System.arraycopy(elementData, index+1, elementData, index,
    22.                                 numMoved);
    23.         elementData[--size] = null; // Let gc do its work
    24. }
    复制代码


      通过remove方法删除元素最终是调用的fastRemove()方法,在fastRemove()方法中,首先对modCount进行加1操作(因为对集合修改了一次),然后接下来就是删除元素的操作,最后将size进行减1操作,并将引用置为null以方便垃圾收集器进行回收工作。
      那么注意此时各个变量的值:对于iterator,其expectedModCount为0,cursor的值为1,lastRet的值为0。
      对于list,其modCount为1,size为0。
      接着看程序代码,执行完删除操作后,继续while循环,调用hasNext方法()判断,由于此时cursor为1,而size为0,那么返回true,所以继续执行while循环,然后继续调用iterator的next()方法:
      注意,此时要注意next()方法中的第一句:checkForComodification()。
      在checkForComodification方法中进行的操作是:

    1. final void checkForComodification() {
    2.     if (modCount != expectedModCount)
    3.         throw new ConcurrentModificationException();
    4. }
    复制代码


      如果modCount不等于expectedModCount,则抛出ConcurrentModificationException异常。
      很显然,此时modCount为1,而expectedModCount为0,因此程序就抛出了ConcurrentModificationException异常。
      到这里,想必大家应该明白为何上述代码会抛出ConcurrentModificationException异常了。
      关键点就在于:调用list.remove()方法导致modCount和expectedModCount的值不一致。
      注意,像使用for-each进行迭代实际上也会出现这种问题。
    二.在单线程环境下的解决办法
      既然知道原因了,那么如何解决呢?
      其实很简单,细心的朋友可能发现在Itr类中也给出了一个remove()方法:

    1. public void remove() {
    2.     if (lastRet == -1)
    3.         throw new IllegalStateException();
    4.        checkForComodification();
    5.     try {
    6.         AbstractList.this.remove(lastRet);
    7.         if (lastRet < cursor)
    8.             cursor--;
    9.         lastRet = -1;
    10.         expectedModCount = modCount;
    11.     } catch (IndexOutOfBoundsException e) {
    12.         throw new ConcurrentModificationException();
    13.     }
    14. }
    复制代码


      在这个方法中,删除元素实际上调用的就是list.remove()方法,但是它多了一个操作:

    1. expectedModCount = modCount;
    复制代码


      因此,在迭代器中如果要删除元素的话,需要调用Itr类的remove方法。
      将上述代码改为下面这样就不会报错了:

    1. public class Test {
    2.         public static void main(String[] args)  {
    3.                 ArrayList<Integer> list = new ArrayList<Integer>();
    4.                 list.add(2);
    5.                 Iterator<Integer> iterator = list.iterator();
    6.                 while(iterator.hasNext()){
    7.                         Integer integer = iterator.next();
    8.                         if(integer==2)
    9.                                 iterator.remove();   //注意这个地方
    10.                 }
    11.         }
    12. }
    复制代码


    三.在多线程环境下的解决方法
      上面的解决办法在单线程环境下适用,但是在多线程下适用吗?看下面一个例子:

    1. public class Test {
    2.         static ArrayList<Integer> list = new ArrayList<Integer>();
    3.         public static void main(String[] args)  {
    4.                 list.add(1);
    5.                 list.add(2);
    6.                 list.add(3);
    7.                 list.add(4);
    8.                 list.add(5);
    9.                 Thread thread1 = new Thread(){
    10.                         public void run() {
    11.                                 Iterator<Integer> iterator = list.iterator();
    12.                                 while(iterator.hasNext()){
    13.                                         Integer integer = iterator.next();
    14.                                         System.out.println(integer);
    15.                                         try {
    16.                                                 Thread.sleep(100);
    17.                                         } catch (InterruptedException e) {
    18.                                                 e.printStackTrace();
    19.                                         }
    20.                                 }
    21.                         };
    22.                 };
    23.                 Thread thread2 = new Thread(){
    24.                         public void run() {
    25.                                 Iterator<Integer> iterator = list.iterator();
    26.                                 while(iterator.hasNext()){
    27.                                         Integer integer = iterator.next();
    28.                                         if(integer==2)
    29.                                                 iterator.remove();  
    30.                                 }
    31.                         };
    32.                 };
    33.                 thread1.start();
    34.                 thread2.start();
    35.         }
    36. }
    复制代码


      运行结果:
      
      有可能有朋友说ArrayList是非线程安全的容器,换成Vector就没问题了,实际上换成Vector还是会出现这种错误。
      原因在于,虽然Vector的方法采用了synchronized进行了同步,但是实际上通过Iterator访问的情况下,每个线程里面返回的是不同的iterator,也即是说expectedModCount是每个线程私有。假若此时有2个线程,线程1在进行遍历,线程2在进行修改,那么很有可能导致线程2修改后导致Vector中的modCount自增了,线程2的expectedModCount也自增了,但是线程1的expectedModCount没有自增,此时线程1遍历时就会出现expectedModCount不等于modCount的情况了。
      因此一般有2种解决办法:
      1)在使用iterator迭代的时候使用synchronized或者Lock进行同步;
      2)使用并发容器CopyOnWriteArrayList代替ArrayList和Vector。
      关于并发容器的内容将在下一篇文章中讲述。
      参考资料:
      http://blog.csdn.net/izard999/article/details/6708738
      http://www.2cto.com/kf/201403/286536.html
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-19 13:05 , Processed in 0.433386 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表