Fail-Fast 与 Fail-Safe 机制
相信不少同学都遇到过在遍历集合的同时,判断满足某些条件的时候 remove 元素,然后报错的情况,这其实是 Java 中集合的 Fail-Fast 机制在起作用,下面来看下什么是 Fail-Fast 机制~
Fail-Fast
是 Java 集合的一种错误检测机制。当遍历集合的同时修改集合或多线程对集合进行结构上的改变操作时,有可能会产生 fail-fast 机制,会抛出 ConcurrentModificationException
异常。
集合(如,常用的 ArrayList
)的迭代器在调用 next()、remove() 方法时,都会调用 checkForComodification
方法检测 modCount == expectedModCount
是否成立,若不成立,则抛出 ConcurrentModificationException
异常,也就是 fail-fast 机制。modCount 是每次改变集合数量时,都会改变的值。
ArrayList
的内部类 Itr
的源码
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; // 初始化 expectedModCount 为 modCount 的值
public E next() {
checkForComodification();
...
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
...
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
// 修正 expectedModCount 值
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
可以看到迭代器在每次调用 next()
、remove()
方法前,都会调用 checkForComodification()
方法检查 modCount
和 expectedModCount
的值是否相等,不相等则抛出 ConcurrentModificationException
异常。expectedModCount
的值默认初始化为 modCount
的值,且只有在调用 Itr
自己的 remove()
方法时,才会修正 expectedModCount
的值。即:
不要在 foreach 循环(增强 for 循环编译后的源码就是使用了迭代器)里调用 ArrayList 自己的 remove/add 操作。请统一使用迭代器
Iterator
方式遍历 + remove 操作,如果是并发操作,需要对 Iterator 对象加锁。
看下面几个例子
如下代码会抛出异常吗?
Q1
List<String> list = Arrays.asList("1", "2", "3", "4");
for (String i : list) {
if ("1".equals(i)) {
list.remove("1");
}
}
不会抛出 ConcurrentModificationException,但是会抛出 UnsupportedOperationException 异常。
Arrays.asList 中生成的 ArrayList 是 Arrays 中的内部类,其中的数组用 final 修饰,不支持增删改,只可以调用 get 和 set 方法。
Q2
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String tmp = iter.next();
System.out.println(tmp);
if (tmp.equals("3")) {
list.remove("3");
}
}
不会。remove 倒数第二个元素(3)之后,cursor 会变为 3,同时数组 size 会减一。迭代器中的 hasNext() 方法会判断当前 cursor(下一个要返回的下标,会在 remove 方法中置为 lastRet,即上一个返回过的元素的下标)与 size 相等,不会进入循环。也就是最后一个元素 “4”,不会访问到
。
// ArrayList.Itr
...
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
public E next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
int i = cursor;
if (i >= limit)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
...
ArrayList.this.remove(lastRet);
cursor = lastRet; // cursor 赋值为 lastRet
lastRet = -1;
expectedModCount = modCount;
limit--;
...
}
public boolean hasNext() {
return cursor != size;
}
...
Q3
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String tmp = iter.next();
System.out.println(tmp);
if (tmp.equals("4")) {
list.remove("4");
}
}
会,问题与上面的有些相似,删除最后一个元素后,数组 size 变成 3,cursor 是 4,hasNext() 判断不相等,会再次进入循环,则抛出异常。
public E next() {
...
if (i >= limit)
throw new NoSuchElementException();
...
}
如何避免 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