fail-fast 机制介绍
fail-fast
(快速失败)机制是集合中比较常见的错误检测机制,防止在对集合进行遍历的时候,出现意料之外的修改,导致意想不到的结果
fail-fast 产生原因
下面通过一个简单的例子分析fail-fast
产生的原因
@Test
public void failFastTest(){
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
list.add("4");
}
}
代码执行结果
通过控制台输出报错信息,可以看到ConcurrentModificationException
异常是调用iterator.next()
方法的时候跑抛出的,进入到next()
方法
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];
}
可以看到next()
方法在每次调用的时候,会先调用checkForComdification()
方法,进入到checkForComdification()
方法
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
代码比较简单,当modCount
与expectedModCount
不相等的时候,就抛出ConcurrentModficationException
异常
modCount
是ArrayList
中的一个成员变量,表示的是ArrayList
被修改的次数,每次调用ArrayLsit
的add(E e)
/remove()
方法时,modCount++
expectedModCount
是ArrayList
中的一个内部类Itr
的成员变量,其值是在ArrayList.iterator()
方法被调用的时候初始化的,取初始化那一刻的modCount
的值。表示的是ArrayList
预计被修改的次数
当我们在对ArrayList
进行迭代的时候,对集合进行修改,就会产生modeCount != expectedModCount
,程序抛出ConcurrentModficationException
fail-fast 更多是在多线程场景下产生的,上面的例子只是为了简单讲解 fail-fast 产生的原因
公众号
扫码关注我,一起学习,一起进步