ConcurrentModificationException

8/22/2021 Exception

# 场景✨

collection082202_1

# 解决方案✌

collection082202_2

# 原因分析👀

​ Java的for循环,就是将List对象遍历托管给Iterator,你如果要对list进行增删操作,都必须经过Iterator,否则Iterator遍历时会乱,所以直接对list进行删除时,Iterator会抛出ConcurrentModificationException异常。

# 其实,每次foreach迭代的时候都有两部操作:

// 第一步:iterator.hasNext()  判断是否有下个元素
public boolean hasNext() {
            return cursor != size;
        }
1
2
3
4

# 第二步:item = iterator.next()

// 下个元素是什么,并赋值给上面例子中的item变量
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];
        }
1
2
3
4
5
6
7
8
9
10
11
12

# 通过debug调试,我们发现,checkForComodification时返回了异常,异常原因为 modCount != expectedModCount。

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

# 进一步阅读源码,发现

  1. modCount 时List从new开始,被修改的次数。当List调用Remove等方法时,modCount++

  2. expectedModCount是指Iterator现在期望这个list被修改的次数是多少次。是在Iterator初始化的时候将modCount 的值赋给了expectedModCount

# 那么就解释了为什么会报上述异常:

  1. modCount 会随着调用List.remove方法而自动增减,而expectedModCount则不会变化,就导致modCount != expectedModCount。
  2. 在删除倒数第二个元素后,cursor=size-1,此时size=size-1,导致hasNext方法认为遍历结束。

# 解决方法🌼

在找到原因后,则进一步进行解决

经过查阅源码可以发现,iterator也有一个remove方法如下,其中有一个重要的操作为expectedModCount = modCount;这样就保证了两者的相等。

public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
1
2
3
4
5
6
7
8
9
10
11
12
13
14

修改后的代码如下:

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Integer> listA=new ArrayList<>();
        listA.add(1);
        listA.add(2);
        listA.add(3);
        listA.add(4);
        listA.add(5);
        listA.add(6);
        Iterator<Integer> it_b=listA.iterator();
        while(it_b.hasNext()){
            Integer a=it_b.next();
            if (a==4) {
                it_b.remove();
            }
        }
        for(Integer b:listA){
            System.out.println(b);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23