Java源碼解析ArrayList及ConcurrentModificationException
本文基于jdk1.8來分析ArrayList的源碼
首先是主要的成員變量。
/** * Default initial capacity. **/ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances. **/ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. **/ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. **/ transient Object[] elementData; // non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). * * @serial **/ private int size;
其中初始大小為10,size表示集合中元素的個數(shù)。此外,還有兩個空數(shù)組EMPTY_ELEMENTDATA,和DEFAULTCAPACITY_EMPTY_ELEMENTDATA。通過DEFAULTCAPACITY_EMPTY_ELEMENTDATA的注釋,我們可以了解到,這個變量區(qū)別于EMPTY_ELEMENTDATA,主要是為了決定第一個元素插入時,擴容多大的問題。從這里的描述可以理解到,ArrayList創(chuàng)建好后,其實并沒有真正分配數(shù)組空間,而是在第一個元素插入時,才分配的空間。這一點是區(qū)別于jdk1.6的。在jdk1.6中,ArrayList一創(chuàng)建,數(shù)據(jù)空間就默認分配好了,10個或指定的空間。jdk1.8這么做,可以做到空間延遲分配,提高程序性能。
接下來看一下構造函數(shù)。
/** * Constructs an empty list with an initial capacity of ten. **/ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative **/ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } }
無參構造函數(shù),將創(chuàng)建一個長度為0的空數(shù)組。
有參構造函數(shù),參數(shù)大于0時正常創(chuàng)建數(shù)組,參數(shù)為0時,也是創(chuàng)建長度為0的數(shù)組。但它和無參構造函數(shù)創(chuàng)建的空數(shù)組是可以區(qū)別開的,它們使用了不同的對象。
接下來是插入元素add。
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) **/ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
通過calculateCapacity函數(shù),我們可以知道,如果是用new ArrayList()創(chuàng)建的list,第一次add元素,計算得minCapacity = 1。如果是new ArrayList(0)創(chuàng)建的list,計算得minCapacity = 10. 然后再根據(jù)minCapacity去grow。
get方法比較簡單,這里不再分析。
ArrayList的一個常見問題是ConcurrentModificationException,同步修改異常,也稱為快速失敗,fast-fail。當我們以foreach方式遍歷ArrayList時,如果在遍歷過程中刪除ArrayList的元素,或者別的線程往ArrayList中添加元素,就會拋出該異常。這里需要注意,以for(int i = 0; i < list.size(); i++)的方式遍歷ArrayList時,是不會拋出同步修改異常的,但用這種方式遍歷,需要處理好i的前進速度。
那么,用foreach方式遍歷ArrayList為什么會拋出同步修改異常呢?
foreach代碼的底層實現(xiàn),是用iterator對ArrayList進行遍歷,在遍歷過程中,會持續(xù)調用next獲取下一個元素。next方法中,會首先checkForComodification(),它的作用是檢查modCount和expectedModCount是否相等。不相等時,則拋出同步修改異常。那么什么情況下修改次數(shù)和期望修改次數(shù)不相等呢?這里需要首先弄明白,modCount和expectedModCount是什么東西?modCount是ArrayList從它的父類繼承來的屬性,記錄了集合的修改次數(shù),add,remove時都會給modCount加1. expectedModCount是迭代器的成員變量,它是在創(chuàng)建迭代器時,取的modCount的值,并且,在遍歷過程中不再改變。那么就清楚了,expectedModCount其實是開始遍歷時modCount的值,如果在遍歷過程中,ArrayList進行了add或remove操作,那么必然導致expectedModCount和modCount不相等,于是就拋出了同步修改異常。
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]; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
那么,同步修改異常如何避免呢?或者說,我們如何遍歷集合并把其中的某些元素刪除呢?
答案是使用迭代器的remove方法刪除元素。在迭代器的remove方法中,刪除元素后,會重新把modCount賦值給expectedModCount,所以,它不會拋出同步修改異常。
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(); } }
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
- Java ConcurrentModificationException異常解決案例詳解
- 詳解Java刪除Map中元素java.util.ConcurrentModificationException”異常解決
- 出現(xiàn)java.util.ConcurrentModificationException 問題及解決辦法
- java.util.ConcurrentModificationException 解決方法
- java 集合并發(fā)操作出現(xiàn)的異常ConcurrentModificationException
- Java?報錯?java.util.ConcurrentModificationException:?null?的原因及解決方案
相關文章
Spring配置文件解析之BeanDefinitionDocumentReader詳解
這篇文章主要介紹了Spring配置文件解析之BeanDefinitionDocumentReader詳解,Spring的xml配置文件解析成Document對象,接下來的解析處理工作是在BeanDefinitionDocumentReader中對Document對象進行解析,需要的朋友可以參考下2024-02-02Springboot使用Spring Data JPA實現(xiàn)數(shù)據(jù)庫操作
Spring Data JPA 是 Spring 基于 Spring Data 框架、在JPA 規(guī)范的基礎上開發(fā)的一個框架,使用 Spring Data JPA 可以極大地簡化JPA 的寫法,本章我們將詳細介紹在Springboot中使用 Spring Data JPA 來實現(xiàn)對數(shù)據(jù)庫的操作2021-06-06SpringBoot整合mybatis-plus進階詳細教程
本文主要對mybatis-plus的條件構造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動填充等知識點進行講解,需要的朋友參考下吧2021-09-09springboot如何通過session實現(xiàn)單點登入詳解
單點登錄(SSO)的定義是在多個應用系統(tǒng)中,用戶只需要登錄一次就可以訪問所有相互信任的應用系統(tǒng),下面這篇文章主要給大家介紹了關于springboot如何通過session實現(xiàn)單點登入的相關資料,需要的朋友可以參考下2021-12-12