一:快速失败(fail—fast)(使用原有对象)
在用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了修改(增加、删除、修改),则会抛出Concurrent Modification Exception。
原理:迭代器在遍历时直接访问集合中的内容,并且在遍历过程中使用一个 modCount 变量。集合在被遍历期间如果内容发生变化,就会改变modCount的值。每当迭代器使用hashNext()/next()遍历下一个元素之前,都会检测modCount变量是否为expectedmodCount值,是的话就返回遍历;否则抛出异常,终止遍历。
注意:这里异常的抛出条件是检测到 modCount!=expectedmodCount 这个条件。如果集合发生变化时修改modCount值刚好又设置为了expectedmodCount值,则异常不会抛出。因此,不能依赖于这个异常是否抛出而进行并发操作的编程,这个异常只建议用于检测并发修改的bug。
场景:java.util包下的集合类都是快速失败的,不能在多线程下发生并发修改(迭代过程中被修改)。

二:安全失败(fail—safe)(复制原有对象)
采用安全失败机制的集合容器,在遍历时不是直接在集合内容上访问的,而是先复制原有集合内容,在拷贝的集合上进行遍历。
原理:由于迭代时是对原集合的拷贝进行遍历,所以在遍历过程中对原集合所作的修改并不能被迭代器检测到,所以不会触发Concurrent Modification Exception。
缺点:基于拷贝内容的优点是避免了Concurrent Modification Exception,但同样地,迭代器并不能访问到修改后的内容,即:迭代器遍历的是开始遍历那一刻拿到的集合拷贝,在遍历期间原集合发生的修改迭代器是不知道的。
场景:java.util.concurrent包下的容器都是安全失败,可以在多线程下并发使用,并发修改。

Fail-Fast
是 Java 集合的一种错误检测机制。当遍历集合的同时修改集合或多线程对集合进行结构上的改变操作时,有可能会产生 fail-fast 机制,会抛出 ConcurrentModificationException 异常。

集合(如,常用的 ArrayList)的迭代器在调用 next()、remove() 方法时,都会调用 checkForComodification 方法检测 modCount == expectedModCount 是否成立,若不成立,则抛出 ConcurrentModificationException 异常,也就是 fail-fast 机制。modCount 是每次改变集合数量时,都会改变的值。

ArrayList 的内部类 Itr 的源码

 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; // 初始化 expectedModCount 为 modCount 的值
 5     public E next() {
 6             checkForComodification();
 7             ...
 8             if (i >= elementData.length)
 9                 throw new ConcurrentModificationException();
10             cursor = i + 1;
11             return (E) elementData[lastRet = i];
12         }
13 
14         public void remove() {
15             ...
16             checkForComodification();
17 
18             try {
19                 ArrayList.this.remove(lastRet);
20                 cursor = lastRet;
21                 lastRet = -1;
22                 // 修正 expectedModCount 值
23                 expectedModCount = modCount;
24             } catch (IndexOutOfBoundsException ex) {
25                 throw new ConcurrentModificationException();
26             }
27         }
28         final void checkForComodification() {
29             if (modCount != expectedModCount)
30                 throw new ConcurrentModificationException();
31         }
32     }

 

可以看到迭代器在每次调用 next()、remove() 方法前,都会调用 checkForComodification() 方法检查 modCount 和 expectedModCount 的值是否相等,不相等则抛出 ConcurrentModificationException 异常。expectedModCount 的值默认初始化为 modCount 的值,且只有在调用 Itr 自己的 remove() 方法时,才会修正 expectedModCount 的值。即:

不要在 foreach 循环(增强 for 循环编译后的源码就是使用了迭代器)里调用 ArrayList 自己的 remove/add 操作。请统一使用迭代器 Iterator 方式遍历 + remove 操作,如果是并发操作,需要对 Iterator 对象加锁。

看下面几个例子

如下代码会抛出异常吗?

Q1
1 List<String> list = Arrays.asList("1", "2", "3", "4");
2 for (String i : list) {
3     if ("1".equals(i)) {
4         list.remove("1");
5     }
6 }

不会抛出 ConcurrentModificationException,但是会抛出 UnsupportedOperationException 异常。

Arrays.asList 中生成的 ArrayList 是 Arrays 中的内部类,其中的数组用 final 修饰,不支持增删改,只可以调用 get 和 set 方法。

Q2
 1 List<String> list = new ArrayList<>();
 2 list.add("1");
 3 list.add("2");
 4 list.add("3");
 5 list.add("4");
 6 Iterator<String> iter = list.iterator();
 7 while (iter.hasNext()) {
 8     String tmp = iter.next();
 9     System.out.println(tmp);
10     if (tmp.equals("3")) {
11         list.remove("3");
12     }
13 }

 

不会。remove 倒数第二个元素(3)之后,cursor 会变为 3,同时数组 size 会减一。迭代器中的 hasNext() 方法会判断当前 cursor(下一个要返回的下标,会在 remove 方法中置为 lastRet,即上一个返回过的元素的下标)与 size 相等,不会进入循环。也就是最后一个元素 “4”,不会访问到。

 1 // ArrayList.Itr
 2 ...
 3 int cursor;       // index of next element to return
 4 int lastRet = -1; // index of last element returned; -1 if no such
 5 public E next() {
 6     if (modCount != expectedModCount)
 7         throw new ConcurrentModificationException();
 8     int i = cursor;
 9     if (i >= limit)
10         throw new NoSuchElementException();
11     Object[] elementData = ArrayList.this.elementData;
12     if (i >= elementData.length)
13         throw new ConcurrentModificationException();
14     cursor = i + 1;
15     return (E) elementData[lastRet = i];
16 }
17 public void remove() {
18     ...
19     ArrayList.this.remove(lastRet);
20     cursor = lastRet; // cursor 赋值为 lastRet
21     lastRet = -1;
22     expectedModCount = modCount;
23     limit--;
24     ...
25 }
26 public boolean hasNext() {
27     return cursor != size;
28 }
29 ...

 

Q3
 1 List<String> list = new ArrayList<>();
 2 list.add("1");
 3 list.add("2");
 4 list.add("3");
 5 list.add("4");
 6 Iterator<String> iter = list.iterator();
 7 while (iter.hasNext()) {
 8     String tmp = iter.next();
 9     System.out.println(tmp);
10     if (tmp.equals("4")) {
11         list.remove("4");
12     }
13 }

会,问题与上面的有些相似,删除最后一个元素后,数组 size 变成 3,cursor 是 4,hasNext() 判断不相等,会再次进入循环,则抛出异常。

1 public E next() {
2     ...
3     if (i >= limit)
4         throw new NoSuchElementException();
5     ...
6 }

如何避免 fail-fast 异常
如果要在遍历时修改集合,使用迭代器的 remove 方法,迭代器的 remove 方法会修正其内部的 expectedModCount 值。
并发环境,需要对 Iterator 对象加锁
使用 Collections.synchronizedList
使用 CopyOnWriteArrayList(采用 fail-safe 机制)
Fail-Safe
Fail-Safe 机制与 Fail-Fast 机制相反,为了避免 Fail-Fast 机制抛出异常,在迭代器的实现上去掉了 modCount 的 ConcurrentModificationException 检查机制。避免了 Fail-Fast。

使用 Fail-Safe 机制的容器 - CopyOnWriteArrayList