由ArrayList來(lái)深入理解Java中的fail-fast機(jī)制
1. fail-fast簡(jiǎn)介
“快速失敗”也就是fail-fast,它是Java集合的一種錯(cuò)誤檢測(cè)機(jī)制。某個(gè)線程在對(duì)collection進(jìn)行迭代時(shí),不允許其他線程對(duì)該collection進(jìn)行結(jié)構(gòu)上的修改。
例如:假設(shè)存在兩個(gè)線程(線程1、線程2),線程1通過(guò)Iterator在遍歷集合A中的元素,在某個(gè)時(shí)候線程2修改了集合A的結(jié)構(gòu)(是結(jié)構(gòu)上面的修改,而不是簡(jiǎn)單的修改集合元素的內(nèi)容),那么這個(gè)時(shí)候程序就會(huì)拋出 ConcurrentModificationException 異常,從而產(chǎn)生fail-fast。
迭代器的快速失敗行為無(wú)法得到保證,它不能保證一定會(huì)出現(xiàn)該錯(cuò)誤,因此,ConcurrentModificationException應(yīng)該僅用于檢測(cè) bug。
Java.util包中的所有集合類都是快速失敗的,而java.util.concurrent包中的集合類都是安全失敗的;
快速失敗的迭代器拋出ConcurrentModificationException,而安全失敗的迭代器從不拋出這個(gè)異常。
2 fail-fast示例
示例代碼:(FastFailTest.java)
import java.util.*; import java.util.concurrent.*; /* * @desc java集合中Fast-Fail的測(cè)試程序。 * * fast-fail事件產(chǎn)生的條件:當(dāng)多個(gè)線程對(duì)Collection進(jìn)行操作時(shí),若其中某一個(gè)線程通過(guò)iterator去遍歷集合時(shí),該集合的內(nèi)容被其他線程所改變;則會(huì)拋出ConcurrentModificationException異常。 * fast-fail解決辦法:通過(guò)util.concurrent集合包下的相應(yīng)類去處理,則不會(huì)產(chǎn)生fast-fail事件。 * * 本例中,分別測(cè)試ArrayList和CopyOnWriteArrayList這兩種情況。ArrayList會(huì)產(chǎn)生fast-fail事件,而CopyOnWriteArrayList不會(huì)產(chǎn)生fast-fail事件。 * (01) 使用ArrayList時(shí),會(huì)產(chǎn)生fast-fail事件,拋出ConcurrentModificationException異常;定義如下: * private static List<String> list = new ArrayList<String>(); * (02) 使用時(shí)CopyOnWriteArrayList,不會(huì)產(chǎn)生fast-fail事件;定義如下: * private static List<String> list = new CopyOnWriteArrayList<String>(); * * @author skywang */ public class FastFailTest { private static List<String> list = new ArrayList<String>(); //private static List<String> list = new CopyOnWriteArrayList<String>(); public static void main(String[] args) { // 同時(shí)啟動(dòng)兩個(gè)線程對(duì)list進(jìn)行操作! new ThreadOne().start(); new ThreadTwo().start(); } private static void printAll() { System.out.println(""); String value = null; Iterator iter = list.iterator(); while(iter.hasNext()) { value = (String)iter.next(); System.out.print(value+", "); } } /** * 向list中依次添加0,1,2,3,4,5,每添加一個(gè)數(shù)之后,就通過(guò)printAll()遍歷整個(gè)list */ private static class ThreadOne extends Thread { public void run() { int i = 0; while (i<6) { list.add(String.valueOf(i)); printAll(); i++; } } } /** * 向list中依次添加10,11,12,13,14,15,每添加一個(gè)數(shù)之后,就通過(guò)printAll()遍歷整個(gè)list */ private static class ThreadTwo extends Thread { public void run() { int i = 10; while (i<16) { list.add(String.valueOf(i)); printAll(); i++; } } } }
運(yùn)行結(jié)果
運(yùn)行該代碼,拋出異常java.util.ConcurrentModificationException!即,產(chǎn)生fail-fast事件!
結(jié)果說(shuō)明
(01) FastFailTest中通過(guò) new ThreadOne().start() 和 new ThreadTwo().start() 同時(shí)啟動(dòng)兩個(gè)線程去操作list。
ThreadOne線程:向list中依次添加0,1,2,3,4,5。每添加一個(gè)數(shù)之后,就通過(guò)printAll()遍歷整個(gè)list。
ThreadTwo線程:向list中依次添加10,11,12,13,14,15。每添加一個(gè)數(shù)之后,就通過(guò)printAll()遍歷整個(gè)list。
(02) 當(dāng)某一個(gè)線程遍歷list的過(guò)程中,list的內(nèi)容被另外一個(gè)線程所改變了;就會(huì)拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。
3. fail-fast解決辦法
fail-fast機(jī)制,是一種錯(cuò)誤檢測(cè)機(jī)制。它只能被用來(lái)檢測(cè)錯(cuò)誤,因?yàn)镴DK并不保證fail-fast機(jī)制一定會(huì)發(fā)生。若在多線程環(huán)境下使用fail-fast機(jī)制的集合,建議使用“java.util.concurrent包下的類”去取代“java.util包下的類”。
所以,本例中只需要將ArrayList替換成java.util.concurrent包下對(duì)應(yīng)的類即可。 即,將代碼
private static List<String> list = new ArrayList<String>();
替換為
private static List<String> list = new CopyOnWriteArrayList<String>();
則可以解決該辦法。
4. fail-fast原理
產(chǎn)生fail-fast事件,是通過(guò)拋出ConcurrentModificationException異常來(lái)觸發(fā)的。
那么,ArrayList是如何拋出ConcurrentModificationException異常的呢?
我們知道,ConcurrentModificationException是在操作Iterator時(shí)拋出的異常。我們先看看Iterator的源碼。ArrayList的Iterator是在父類AbstractList.java中實(shí)現(xiàn)的。代碼如下:
package java.util;
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { ... // AbstractList中唯一的屬性 // 用來(lái)記錄List修改的次數(shù):每修改一次(添加/刪除等操作),將modCount+1 protected transient int modCount = 0; // 返回List對(duì)應(yīng)迭代器。實(shí)際上,是返回Itr對(duì)象。 public Iterator<E> iterator() { return new Itr(); } // Itr是Iterator(迭代器)的實(shí)現(xiàn)類 private class Itr implements Iterator<E> { int cursor = 0; int lastRet = -1; // 修改數(shù)的記錄值。 // 每次新建Itr()對(duì)象時(shí),都會(huì)保存新建該對(duì)象時(shí)對(duì)應(yīng)的modCount; // 以后每次遍歷List中的元素的時(shí)候,都會(huì)比較expectedModCount和modCount是否相等; // 若不相等,則拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。 int expectedModCount = modCount; public boolean hasNext() { return cursor != size(); } public E next() { // 獲取下一個(gè)元素之前,都會(huì)判斷“新建Itr對(duì)象時(shí)保存的modCount”和“當(dāng)前的modCount”是否相等; // 若不相等,則拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。 checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } ... }
從中,我們可以發(fā)現(xiàn)在調(diào)用 next() 和 remove()時(shí),都會(huì)執(zhí)行 checkForComodification()。若 “modCount 不等于 expectedModCount”,則拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。
要搞明白 fail-fast機(jī)制,我們就要需要理解什么時(shí)候“modCount 不等于 expectedModCount”!
從Itr類中,我們知道 expectedModCount 在創(chuàng)建Itr對(duì)象時(shí),被賦值為 modCount。通過(guò)Itr,我們知道:expectedModCount不可能被修改為不等于 modCount。所以,需要考證的就是modCount何時(shí)會(huì)被修改。
接下來(lái),我們查看ArrayList的源碼,來(lái)看看modCount是如何被修改的。
package java.util; public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { ... // list中容量變化時(shí),對(duì)應(yīng)的同步函數(shù) public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } } // 添加元素到隊(duì)列最后 public boolean add(E e) { // 修改modCount ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; return true; } // 添加元素到指定的位置 public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); // 修改modCount ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } // 添加集合 public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; // 修改modCount ensureCapacity(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } // 刪除指定位置的元素 public E remove(int index) { RangeCheck(index); // 修改modCount modCount++; E oldValue = (E) elementData[index]; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; } // 快速刪除指定位置的元素 private void fastRemove(int index) { // 修改modCount modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work } // 清空集合 public void clear() { // 修改modCount modCount++; // Let gc do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } ... }
從中,我們發(fā)現(xiàn):無(wú)論是add()、remove(),還是clear(),只要涉及到修改集合中的元素個(gè)數(shù)時(shí),都會(huì)改變modCount的值。
接下來(lái),我們?cè)傧到y(tǒng)的梳理一下fail-fast是怎么產(chǎn)生的。步驟如下:
(01) 新建了一個(gè)ArrayList,名稱為arrayList。
(02) 向arrayList中添加內(nèi)容。
(03) 新建一個(gè)“線程a”,并在“線程a”中通過(guò)Iterator反復(fù)的讀取arrayList的值。
(04) 新建一個(gè)“線程b”,在“線程b”中刪除arrayList中的一個(gè)“節(jié)點(diǎn)A”。
(05) 這時(shí),就會(huì)產(chǎn)生有趣的事件了。
在某一時(shí)刻,“線程a”創(chuàng)建了arrayList的Iterator。此時(shí)“節(jié)點(diǎn)A”仍然存在于arrayList中,創(chuàng)建arrayList時(shí),expectedModCount = modCount(假設(shè)它們此時(shí)的值為N)。
在“線程a”在遍歷arrayList過(guò)程中的某一時(shí)刻,“線程b”執(zhí)行了,并且“線程b”刪除了arrayList中的“節(jié)點(diǎn)A”?!熬€程b”執(zhí)行remove()進(jìn)行刪除操作時(shí),在remove()中執(zhí)行了“modCount++”,此時(shí)modCount變成了N+1!
“線程a”接著遍歷,當(dāng)它執(zhí)行到next()函數(shù)時(shí),調(diào)用checkForComodification()比較“expectedModCount”和“modCount”的大??;而“expectedModCount=N”,“modCount=N+1”,這樣,便拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。
至此,我們就完全了解了fail-fast是如何產(chǎn)生的!
即,當(dāng)多個(gè)線程對(duì)同一個(gè)集合進(jìn)行操作的時(shí)候,某線程訪問(wèn)集合的過(guò)程中,該集合的內(nèi)容被其他線程所改變(即其它線程通過(guò)add、remove、clear等方法,改變了modCount的值);這時(shí),就會(huì)拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。
5. 解決fail-fast的原理
上面,說(shuō)明了“解決fail-fast機(jī)制的辦法”,也知道了“fail-fast產(chǎn)生的根本原因”。接下來(lái),我們?cè)龠M(jìn)一步談?wù)刯ava.util.concurrent包中是如何解決fail-fast事件的。
還是以和ArrayList對(duì)應(yīng)的CopyOnWriteArrayList進(jìn)行說(shuō)明。我們先看看CopyOnWriteArrayList的源碼:
package java.util.concurrent; import java.util.*; import java.util.concurrent.locks.*; import sun.misc.Unsafe; public class CopyOnWriteArrayList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { ... // 返回集合對(duì)應(yīng)的迭代器 public Iterator<E> iterator() { return new集合類中的fast-fail實(shí)現(xiàn)方式都差不多,我們以最簡(jiǎn)單的ArrayList為例吧。protected transient int modCount = 0;記錄的是我們對(duì)ArrayList修改的次數(shù),比如我們調(diào)用 add(),remove()等改變數(shù)據(jù)的操作時(shí),會(huì)將modCount++。protected transient int modCount = 0;記錄的是我們對(duì)ArrayList修改的次數(shù),比如我們調(diào)用 add(),remove()等改變數(shù)據(jù)的操作時(shí),會(huì)將modCount++。 COWIterator<E>(getArray(), 0); } ... private static class COWIterator<E> implements ListIterator<E> { private final Object[] snapshot; private int cursor; private COWIterator(Object[] elements, int initialCursor) { cursor = initialCursor; // 新建COWIterator時(shí),將集合中的元素保存到一個(gè)新的拷貝數(shù)組中。 // 這樣,當(dāng)原始集合的數(shù)據(jù)改變,拷貝數(shù)據(jù)中的值也不會(huì)變化。 snapshot = elements; } public boolean hasNext() { return cursor < snapshot.length; } public boolean hasPrevious() { return cursor > 0; } public E next() { if (! hasNext()) throw new NoSuchElementException(); return (E) snapshot[cursor++]; } public E previous() { if (! hasPrevious()) throw new NoSuchElementException(); return (E) snapshot[--cursor]; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor-1; } public void remove() { throw new UnsupportedOperationException(); } public void set(E e) { throw new UnsupportedOperationException(); } public void add(E e) { throw new UnsupportedOperationException(); } } ... }
從中,我們可以看出:
(01) 和ArrayList繼承于AbstractList不同,CopyOnWriteArrayList沒(méi)有繼承于AbstractList,它僅僅只是實(shí)現(xiàn)了List接口。
(02) ArrayList的iterator()函數(shù)返回的Iterator是在AbstractList中實(shí)現(xiàn)的;而CopyOnWriteArrayList是自己實(shí)現(xiàn)Iterator。
(03) ArrayList的Iterator實(shí)現(xiàn)類中調(diào)用next()時(shí),會(huì)“調(diào)用checkForComodification()比較‘expectedModCount'和‘modCount'的大小”;但是,CopyOnWriteArrayList的Iterator實(shí)現(xiàn)類中,沒(méi)有所謂的checkForComodification(),更不會(huì)拋出ConcurrentModificationException異常!
6. 總結(jié)
由于HashMap(ArrayList)并不是線程安全的,因此如果在使用迭代器的過(guò)程中有其他線程修改了map(這里的修改是指結(jié)構(gòu)上的修改,并非指單純修改集合內(nèi)容的元素),那么將要拋出ConcurrentModificationException 即為fail-fast策略
主要通過(guò)modCount域來(lái)實(shí)現(xiàn),保證線程之間的可見(jiàn)性,modCount即為修改次數(shù),對(duì)于HashMap(ArrayList)內(nèi)容的修改就會(huì)增加這個(gè)值, 那么在迭代器的初始化過(guò)程中就會(huì)將這個(gè)值賦值給迭代器的expectedModCount
但是fail-fast行為并不能保證,因此依賴于此異常的程序的做法是錯(cuò)誤的
相關(guān)文章
Java服務(wù)端如何解決跨域問(wèn)題?CORS請(qǐng)求頭方式
這篇文章主要介紹了Java服務(wù)端如何解決跨域問(wèn)題?CORS請(qǐng)求頭方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11通過(guò)openOffice將office文件轉(zhuǎn)成pdf
這篇文章主要介紹了通過(guò)openOffice將office文件轉(zhuǎn)成pdf,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Java統(tǒng)計(jì)字符串中字符出現(xiàn)次數(shù)的方法示例
這篇文章主要介紹了Java統(tǒng)計(jì)字符串中字符出現(xiàn)次數(shù)的方法,涉及Java針對(duì)字符串的遍歷、查找、計(jì)算等相關(guān)操作技巧,需要的朋友可以參考下2017-12-12里氏代換原則_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了里氏代換原則的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08Java 匯編JVM編寫(xiě)jasmin程序的操作方法
這篇文章主要介紹了Java 匯編JVM編寫(xiě)jasmin程序的操作方法,本文通過(guò)幾個(gè)示例講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04