淺談fail-fast機制

来源:https://www.cnblogs.com/pengx/archive/2018/09/03/9576613.html
-Advertisement-
Play Games

fail-fast機制即為快速失敗機制,個人認為是一種防護措施,在集合結構發生改變的時候,使盡全力拋出ConcurrentModificationException,所以該機制大部分用途都是用來檢測Bug的; 下麵的代碼可以引發fail-fast fail-fast原理 每個集合都會實現可遍歷的介面 ...


fail-fast機制即為快速失敗機制,個人認為是一種防護措施,在集合結構發生改變的時候,使盡全力拋出ConcurrentModificationException,所以該機制大部分用途都是用來檢測Bug的;

下麵的代碼可以引發fail-fast

 

 1     public static void main(String[] args) {
 2         List<String> list = new ArrayList<>();
 3         for (int i = 0 ; i < 10 ; i++ ) {
 4             list.add(i + "");
 5         }
 6         Iterator<String> iterator = list.iterator();
 7         int i = 0 ;
 8         while(iterator.hasNext()) {
 9             if (i == 3) {
10                 list.remove(3);
11                 //list.add("11");   添加元素同樣會引發
12             }
13             System.out.println(iterator.next());
14             i ++;
15         }
16     }

fail-fast原理

每個集合都會實現可遍歷的介面,以上述代碼為例,集合調用iterator();方法的時候,其實是返回了一個new Itr();

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

以下是Itr源碼

    /**
     * An optimized version of AbstractList.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;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        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];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

 

Itr有3個重要屬性;

cursor是指集合遍歷過程中的即將遍歷的元素的索引

lastRet是cursor -1,預設為-1,即不存在上一個時,為-1,它主要用於記錄剛剛遍歷過的元素的索引。

expectedModCount它初始值就為ArrayList中的modCount(modCount是抽象類AbstractList中的變數,預設為0,而ArrayList 繼承了AbstractList ,所以也有這個變數,modCount用於記錄集合操作過程中作的修改次數)

由源碼可以看出,該異常就是在調用next()的時候引發的,而調用next()方法的時候會先調用checkForComodification(),該方法判斷expectedModCount與modCount是否相等,如果不等則拋異常了

那麼問題就來了,初始化的時候expectedModCount就被賦值為modCount,而且源碼當中就一直沒有改變過,所以肯定是modCount的值變了

arrayList繼承了abstractList,abstractList有modCount屬性,通過以下源碼我們可以看到,當ArrayList調用add、remove方法,modCount++

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

所以由此可見,對集合的操作中若modCount發生了改變,則會引發fail-fast機制;同時可以看出如果想要移除集合某元素,可以使用迭代器的remove方法,則不會引發fail-fast;

發表該文章也參考了許多另一片文章的內容,詳情地址:https://blog.csdn.net/zymx14/article/details/78394464


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一,easyui datagrid綁定數據的簡單測試: 1.資料庫中的UserInfo表及數據測試: 2.DAL層: //分頁,模糊查詢(pageNum-1)*pageSize+1 從第幾條數據開始,pageNum*pageSize 查詢到那一條結束 //查詢總的條數 3.一般處理程式(UserIn ...
  • JavaScript 的核心概念主要由 語法、變數、數據類型 、操作符、語句、函數組成,這篇文章主要講解的是前面三個,後面三個下一篇文章再講解。 01 語法 熟悉 JavaScript 歷史的人應該都知道,JavaScript 的很多語法和 Java、C 語言類似,所以一些做後端的程式員上手前端很快 ...
  • 原文鏈接:http://blog.csdn.net/zhangerqing 設計模式(Design pattern)是一套被反覆使用、多數人知曉的、經過分類編目的、代碼設計經驗的總結。使用設計模式是為了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性。 毫無疑問,設計模式於己於他人於系統都是多贏的 ...
  • ThreadLocal 概述 ThreadLocal實例僅作為線程局部變數的==操作類==,以及==線程存儲局部變數時的Key==。真正的線程局部變數是存儲在各自線程的本地,通過Thread類中的 進行存儲。 若希望線上程本地存儲多個局部變數需要使用多個ThreadLocal實例進行操作。 Thre ...
  • https://www.cnblogs.com/jiahaoJAVA/p/6244278.html 1 什麼是redis? Redis 是一個基於記憶體的高性能key-value資料庫。 (有空再補充,有理解錯誤或不足歡迎指正) 2 Reids的特點 Redis本質上是一個Key-Value類型的記憶體 ...
  • 題意 約翰要帶N(1≤N≤100000)只牛去參加集會裡的展示活動,這些牛可以是牡牛,也可以是牝牛.牛們要站成一排.但是牡牛是好鬥的,為了避免牡牛鬧出亂子,約翰決定任意兩隻牡牛之間至少要有K(O≤K<N)只牝牛. 請計算一共有多少種排隊的方法.所有牡牛可以看成是相同的,所有牝牛也一樣.答案對5000 ...
  • 俗話說 「不要重覆造輪子」,關於是否有必要不再本次討論範圍。 創建這個項目的主要目的還是提升自己,看看和知名類開源項目的差距以及學習優秀的開源方式。 ...
  • 持續集成(Continuous Integration)指的是,頻繁地(一天多次)將代碼集成到主幹。 持續集成的目的,就是讓產品可以快速迭代,同時還能保持高質量。 它的核心措施是,代碼集成到主幹之前,必須通過自動化測試。只要有一個測試用例失敗,就不能集成。 持續集成可以把工程師從繁瑣的任務中解放出來 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...