可恶!简单的删除集合中的元素竟然报错

开发 后端
什么是快速失败:fail-fast 机制是java集合(Collection)中的一种错误机制。它只能被用来检测错误,因为JDK并不保证fail-fast机制一定会发生。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。

前言

什么是快速失败:fail-fast 机制是java集合(Collection)中的一种错误机制。它只能被用来检测错误,因为JDK并不保证fail-fast机制一定会发生。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。

运行如下代码,即可出现异常:

  1. // 关于fail-fast的一些思考 
  2. public class FailFastTest { 
  3.     public static void main(String[] args) { 
  4.         // 构建ArrayList 
  5.         List<Integer> list = new ArrayList<>(); 
  6.         list.add(1); 
  7.         list.add(2); 
  8.         list.add(3); 
  9.         list.add(4); 
  10.         for (int i : list) { 
  11.             list.remove(1); 
  12.         } 
  13.     } 

控制台会输出如下异常:

为什么要报这个错?途中出错的地方是ArrayList中的代码,定位到该处代码:

  1. final void checkForComodification() { 
  2.     if (modCount != expectedModCount) 
  3.         throw new ConcurrentModificationException(); 

modCount是这个集合修改的次数,这个属性来自AbstractList,而我们的ArrayList是继承了该抽象类的。

  1. protected transient int modCount = 0; 

expectedModCount又是啥呢?当我们进行遍历时候debug一下发现进行forEach循环的时候其实走了下面这个方法iterator,而且遍历这个底层还是走的hasNext方法

  1. public Iterator<E> iterator() { 
  2.     return new Itr(); 

判断是否有下一个元素

  1. public boolean hasNext() { 
  2.             return cursor != size
  3.         } 

next()方法用于获取元素

  1. public E next() { 
  2.          checkForComodification(); // 留意这个方法 
  3.          int i = cursor
  4.          if (i >= size
  5.              throw new NoSuchElementException(); 
  6.          Object[] elementData = ArrayList.this.elementData; 
  7.          if (i >= elementData.length) 
  8.              throw new ConcurrentModificationException(); 
  9.          cursor = i + 1; 
  10.          return (E) elementData[lastRet = i]; 
  11.      } 

点进这个new Itr(),惊喜的发现原来这个expectedModCount是在这里被赋值的而且和modCount一样

  1. private class Itr implements Iterator<E> { 
  2.         int cursor;       // index of next element to return 
  3.         int lastRet = -1; // index of last element returned; -1 if no such 
  4.         int expectedModCount = modCount; // 注意:此处进行赋值 
  5.         ...... 
  6.         ...... 

接下来看下ArrayList的remove()方法,其对modCount进行了增加,这是导致报错的原因

  1. public E remove(int index) { 
  2.     rangeCheck(index); 
  3.  
  4.     modCount++; // 对modCount进行了++的操作 
  5.     E oldValue = elementData(index); 
  6.  
  7.     int numMoved = size - index - 1; 
  8.     if (numMoved > 0) 
  9.         System.arraycopy(elementData, index+1, elementData, index
  10.                          numMoved); 
  11.     elementData[--size] = null; // clear to let GC do its work 
  12.  
  13.     return oldValue; 

上面的next()方法这有调用一个checkForComodification()方法,下面贴一下这方法的代码

  1. final void checkForComodification() { 
  2.     if (modCount != expectedModCount) 
  3.         throw new ConcurrentModificationException(); 

ArrayList里面remove()方法进行了modCount++操作,原来是我们对集合进行操作后改变了modCount导致上面代码成立,从而抛出异常

但是当我们使用Itr类的remove,也就是如下代码进行对元素改动时,不会抛出ConcurrentModificationException异常

  1. public void remove() { 
  2.        if (lastRet < 0) 
  3.            throw new IllegalStateException(); 
  4.        checkForComodification(); 
  5.  
  6.        try { 
  7.            ArrayList.this.remove(lastRet); 
  8.            cursor = lastRet; 
  9.            lastRet = -1; 
  10.            // 将ArrayList的modCount赋值给Itr类的expectedModCount  
  11.            //这样再次调用next方法时就不会出现这俩个值不一致 从而避免报错 
  12.            expectedModCount = modCount;  
  13.        } catch (IndexOutOfBoundsException ex) { 
  14.            throw new ConcurrentModificationException(); 
  15.        } 
  16.    } 

与ArrayList的remove()方法不同的是,该remove()方法调用ArrayList.this.remove(lastRet);后显然modCount++了,但是马上又让expectedModCount = modCount就是这样才不会抛出异常。

梳理整个流程:

1、for循环遍历实质上调用的是Itr类的方法进行遍历(Itr类实现了Iterator)

2、Itr类在构造的时候会将ArrayList的modCount(实际上modCount是AbstractList的属性,但是ArrayList继承了AbstractList)赋值给Itr类的expectedModCount

3、for循环中调用的remove()方法时ArrayList的,这个方法会对modCount进行++操作

4、remove方法调用后,继续遍历会调用Itr的next()方法,而这个next()方法中的checkForComodification()方法会对modCount和expectedModCount进行对比,由于remove方法已经操作过modCount因此这俩个值不会相等,故报错。

如何改进?

1、可以使用Itr中的remove方法进行改进,改进代码如下

  1. public static void main(String[] args) { 
  2.     // 构建ArrayList 
  3.     List<Integer> list = new ArrayList<>(); 
  4.     list.add(1); 
  5.     list.add(2); 
  6.     list.add(3); 
  7.     list.add(4); 
  8.     Iterator<Integer> iterator = list.iterator(); 
  9.     while(iterator.hasNext()) { 
  10.         iterator.next(); 
  11.         iterator.remove(); 
  12.     } 
  13.     System.out.println(list.size()); // 0 

2、使用CopyOnWriterArrayList来代替Arraylist,它对ArrayList的操作时会先复制一份数据出来操作完了再将其更新回去替换掉旧的,所以CopyOnWrite容器只能保证数据的最终一致性,不能保证数据的实时一致性。这是采用了CopyOnWriterArrayList的fail-safe机制,当集合的结构被改变的时候,fail-safe机制会在复制原集合的一份数据出来,然后在复制的那份数据遍历,fail-safe机制,在JUC包的集合都是有这种机制实现的。

虽然fail-safe不会抛出异常,但存在以下缺点

1、复制时需要额外的空间和时间上的开销。

2、不能保证遍历的是最新内容。

总结

 

对于fail-fast机制,我们要操作List集合时可以使用Iterator的remove()方法在遍历过程中删除元素,或者使用fail-safe机制的CopyOnWriterArrayList,当然使用的时候需要权衡下利弊,结合相关业务场景。

 

责任编辑:武晓燕 来源: 程序员巴士
相关推荐

2012-05-29 15:29:14

JavaArrayList

2012-03-19 09:57:09

JavaArrayList

2010-07-27 15:14:08

删除telnet

2020-08-06 07:49:57

List元素集合

2020-12-28 07:47:35

动态代理AOP

2015-08-04 09:18:26

JavaArrayList元素

2015-03-25 11:42:52

Java删除特定元素

2020-09-30 14:24:58

PythonSet对象

2023-03-27 08:34:00

配置容器Spring

2012-01-12 13:24:55

Java

2022-04-27 09:40:25

抓包图四次挥手TCP

2010-11-22 12:14:55

MySQL字段

2022-01-20 09:58:44

Python元素列表

2010-05-24 15:07:52

Swap space

2021-07-22 09:53:34

Vector类Java添加元素

2021-12-09 09:02:53

JavaPDF文件iText

2021-12-08 10:36:46

JavaPDF文件

2009-11-25 16:40:55

PHP函数array_

2009-11-24 18:28:44

PHP函数array_

2019-02-13 14:55:22

Windows 10视频删除声音
点赞
收藏

51CTO技术栈公众号