Fail-Fast in Java

__HelloWorld__發表於2018-08-24

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;
        }

相關文章