class Solution {
public void test() {
ArrayList<Integer> array = new ArrayList<>();
for (int i = 6; i > 0; i--) {
array.add(i);
}
for (int i = 0; i < 6; i++) {
if (array.get(i) == 3) array.remove(3);//可以正常运行
break;
}
Iterator<Integer> iterator = array.iterator();
while (iterator.hasNext()) {//ConcurrentModificationException异常
Integer next = iterator.next();
if (next == 5) array.remove(5);
}
for(Integer i:array){//foreach迭代删除也会ConcurrentModificationException异常
if(i==3) array.remove(i);
}
}
}
当异常产生时,直接抛出异常,程序终止;
fail-fast主要是体现在当我们在遍历集合元素的时候,经常会使用迭代器,但在迭代器遍历元素的过程中,如果集合的结构(modCount)被改变的话,就会抛出异常ConcurrentModificationException,防止继续遍历。这就是所谓的快速失败机制。
与之对应的就是安全失败:
java.util.concurrent包下的容器都是安全失败,可以在多线程下并发使用,并发修改。