Java源碼解析ArrayList及ConcurrentModificationException
本文基于jdk1.8來(lái)分析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表示集合中元素的個(gè)數(shù)。此外,還有兩個(gè)空數(shù)組EMPTY_ELEMENTDATA,和DEFAULTCAPACITY_EMPTY_ELEMENTDATA。通過(guò)DEFAULTCAPACITY_EMPTY_ELEMENTDATA的注釋,我們可以了解到,這個(gè)變量區(qū)別于EMPTY_ELEMENTDATA,主要是為了決定第一個(gè)元素插入時(shí),擴(kuò)容多大的問題。從這里的描述可以理解到,ArrayList創(chuàng)建好后,其實(shí)并沒有真正分配數(shù)組空間,而是在第一個(gè)元素插入時(shí),才分配的空間。這一點(diǎn)是區(qū)別于jdk1.6的。在jdk1.6中,ArrayList一創(chuàng)建,數(shù)據(jù)空間就默認(rèn)分配好了,10個(gè)或指定的空間。jdk1.8這么做,可以做到空間延遲分配,提高程序性能。
接下來(lái)看一下構(gòu)造函數(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); } }
無(wú)參構(gòu)造函數(shù),將創(chuàng)建一個(gè)長(zhǎng)度為0的空數(shù)組。
有參構(gòu)造函數(shù),參數(shù)大于0時(shí)正常創(chuàng)建數(shù)組,參數(shù)為0時(shí),也是創(chuàng)建長(zhǎng)度為0的數(shù)組。但它和無(wú)參構(gòu)造函數(shù)創(chuàng)建的空數(shù)組是可以區(qū)別開的,它們使用了不同的對(duì)象。
接下來(lái)是插入元素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); }
通過(guò)calculateCapacity函數(shù),我們可以知道,如果是用new ArrayList()創(chuàng)建的list,第一次add元素,計(jì)算得minCapacity = 1。如果是new ArrayList(0)創(chuàng)建的list,計(jì)算得minCapacity = 10. 然后再根據(jù)minCapacity去grow。
get方法比較簡(jiǎn)單,這里不再分析。
ArrayList的一個(gè)常見問題是ConcurrentModificationException,同步修改異常,也稱為快速失敗,fast-fail。當(dāng)我們以foreach方式遍歷ArrayList時(shí),如果在遍歷過(guò)程中刪除ArrayList的元素,或者別的線程往ArrayList中添加元素,就會(huì)拋出該異常。這里需要注意,以for(int i = 0; i < list.size(); i++)的方式遍歷ArrayList時(shí),是不會(huì)拋出同步修改異常的,但用這種方式遍歷,需要處理好i的前進(jìn)速度。
那么,用foreach方式遍歷ArrayList為什么會(huì)拋出同步修改異常呢?
foreach代碼的底層實(shí)現(xiàn),是用iterator對(duì)ArrayList進(jìn)行遍歷,在遍歷過(guò)程中,會(huì)持續(xù)調(diào)用next獲取下一個(gè)元素。next方法中,會(huì)首先checkForComodification(),它的作用是檢查modCount和expectedModCount是否相等。不相等時(shí),則拋出同步修改異常。那么什么情況下修改次數(shù)和期望修改次數(shù)不相等呢?這里需要首先弄明白,modCount和expectedModCount是什么東西?modCount是ArrayList從它的父類繼承來(lái)的屬性,記錄了集合的修改次數(shù),add,remove時(shí)都會(huì)給modCount加1. expectedModCount是迭代器的成員變量,它是在創(chuàng)建迭代器時(shí),取的modCount的值,并且,在遍歷過(guò)程中不再改變。那么就清楚了,expectedModCount其實(shí)是開始遍歷時(shí)modCount的值,如果在遍歷過(guò)程中,ArrayList進(jìn)行了add或remove操作,那么必然導(dǎo)致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(); }
那么,同步修改異常如何避免呢?或者說(shuō),我們?nèi)绾伪闅v集合并把其中的某些元素刪除呢?
答案是使用迭代器的remove方法刪除元素。在迭代器的remove方法中,刪除元素后,會(huì)重新把modCount賦值給expectedModCount,所以,它不會(huì)拋出同步修改異常。
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(); } }
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
- Java ConcurrentModificationException異常解決案例詳解
- 詳解Java刪除Map中元素java.util.ConcurrentModificationException”異常解決
- 出現(xiàn)java.util.ConcurrentModificationException 問題及解決辦法
- java.util.ConcurrentModificationException 解決方法
- java 集合并發(fā)操作出現(xiàn)的異常ConcurrentModificationException
- Java?報(bào)錯(cuò)?java.util.ConcurrentModificationException:?null?的原因及解決方案
相關(guān)文章
Spring配置文件解析之BeanDefinitionDocumentReader詳解
這篇文章主要介紹了Spring配置文件解析之BeanDefinitionDocumentReader詳解,Spring的xml配置文件解析成Document對(duì)象,接下來(lái)的解析處理工作是在BeanDefinitionDocumentReader中對(duì)Document對(duì)象進(jìn)行解析,需要的朋友可以參考下2024-02-02Springboot使用Spring Data JPA實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
Spring Data JPA 是 Spring 基于 Spring Data 框架、在JPA 規(guī)范的基礎(chǔ)上開發(fā)的一個(gè)框架,使用 Spring Data JPA 可以極大地簡(jiǎn)化JPA 的寫法,本章我們將詳細(xì)介紹在Springboot中使用 Spring Data JPA 來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的操作2021-06-06SpringBoot整合mybatis-plus進(jìn)階詳細(xì)教程
本文主要對(duì)mybatis-plus的條件構(gòu)造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動(dòng)填充等知識(shí)點(diǎn)進(jìn)行講解,需要的朋友參考下吧2021-09-09java調(diào)用mysql存儲(chǔ)過(guò)程實(shí)例分析
這篇文章主要介紹了java調(diào)用mysql存儲(chǔ)過(guò)程的方法,以實(shí)例形式較為詳細(xì)的分析了mysql數(shù)據(jù)庫(kù)的建立和存儲(chǔ)過(guò)程的實(shí)現(xiàn)方法,需要的朋友可以參考下2015-06-06Java生產(chǎn)1-100的隨機(jī)數(shù)簡(jiǎn)單實(shí)例(分享)
下面小編就為大家?guī)?lái)一篇Java生產(chǎn)1-100的隨機(jī)數(shù)簡(jiǎn)單實(shí)例(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05springboot如何通過(guò)session實(shí)現(xiàn)單點(diǎn)登入詳解
單點(diǎn)登錄(SSO)的定義是在多個(gè)應(yīng)用系統(tǒng)中,用戶只需要登錄一次就可以訪問所有相互信任的應(yīng)用系統(tǒng),下面這篇文章主要給大家介紹了關(guān)于springboot如何通過(guò)session實(shí)現(xiàn)單點(diǎn)登入的相關(guān)資料,需要的朋友可以參考下2021-12-12Java 代碼實(shí)例解析設(shè)計(jì)模式之監(jiān)聽者模式
所謂監(jiān)聽者模式,我理解的是構(gòu)建一個(gè)容器存放所有被監(jiān)聽的線程或?qū)ο?,監(jiān)聽每個(gè)線程或?qū)ο蟀l(fā)生的變化,若某個(gè)線程或?qū)ο笥|發(fā)指定規(guī)則,那么則對(duì)所有被監(jiān)聽的線程或?qū)ο蟾鶕?jù)業(yè)務(wù)需要做處理2021-10-10