A fail-fast system is nothing but immediately report any failure that is likely to lead to failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators. Incase, you have called iterator on a collection object, and another thread tries to modify the collection object, then concurrent modification exception will be thrown. This is called fail-fast.
Fail-Fast:又称“快速失败”或“早期失败”是一个软件工程概念,是指当异常发生时,立即停止执行以防止复杂问题的发生。
在Java语言中,由集合类比如:ArrayList, HashSet, Vector等等所返回的迭代器对象都是Fail-Fast的,也就是说,当你通过迭代器Iterator来遍历集合内的对象,同时又对集合进行修改(增加add或者删除remove)操作时,就会抛出ConcurrentModificationException异常。
我们看下面这个例子:
List<Integer> ints = new ArrayList<>(asList(1, 2, 3, 4, 5, 6, 9, 15, 67, 23, 22, 3, 1, 4, 2));
for (Integer i : ints) {
// some code
ints.add(57); // throws java.util.ConcurrentModificationException
}
当你执行时,你就会得到以下异常:
Exception in thread "main" java.util.ConcurrentModificationException
1
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at simulate.SetTest.main(SetTest.java:40)
在Java 8u20 发行版本中,Collections.sort()同样也是一个Fail-Fast,这也意味着你无法在对集合迭代遍历的同时执行Collections.sort()排序操作,比如类似下面这样:
List<Integer> ints = new ArrayList<>(asList(1, 2, 3, 4, 5, 6, 9, 15, 67));
for (Integer i : ints) {
// some code
Collections.sort(ints);
}
这么设计是有意义的,如果你在迭代遍历的同时执行排序操作,不仅违反正常的语义,而且还容易引起未知的后果,当然,你在调用Collections.sort()方法之后,立即跳出迭代(break),那就不会引起该异常,但通常这不是推荐做法。
List<Integer> ints = new ArrayList<>(asList(1, 2, 3, 4, 5, 6, 9, 15, 67));
for (Integer i : ints) {
// some code
Collections.sort(ints);
break;
}