概要
前面娇唯,我們已經學習了ArrayList。接下來寂玲,我們以ArrayList為例视乐,對Iterator的fail-fast機制進行了解。內容包括::
1 fail-fast簡介
fail-fast 機制是java集合(Collection)中的一種錯誤機制敢茁。當多個線程對同一個集合的內容進行操作時佑淀,就可能會產生fail-fast事件。
例如:當某一個線程A通過iterator去遍歷某集合的過程中彰檬,若該集合的內容被其他線程所改變了伸刃;那么線程A訪問集合時,就會拋出ConcurrentModificationException異常逢倍,產生fail-fast事件捧颅。
在詳細介紹fail-fast機制的原理之前,先通過一個示例來認識fail-fast较雕。
2 fail-fast示例
示例代碼:(FastFailTest.java)
import java.util.*;
import java.util.concurrent.*;
/*
* @desc java集合中Fast-Fail的測試程序碉哑。
*
*? fast-fail事件產生的條件:當多個線程對Collection進行操作時挚币,若其中某一個線程通過iterator去遍歷集合時,該集合的內容被其他線程所改變扣典;則會拋出ConcurrentModificationException異常妆毕。
*? fast-fail解決辦法:通過util.concurrent集合包下的相應類去處理,則不會產生fast-fail事件贮尖。
*
*? 本例中笛粘,分別測試ArrayList和CopyOnWriteArrayList這兩種情況。ArrayList會產生fast-fail事件湿硝,而CopyOnWriteArrayList不會產生fast-fail事件薪前。
*? (01) 使用ArrayList時任斋,會產生fast-fail事件馏锡,拋出ConcurrentModificationException異常;定義如下:
*? ? ? ? ? ? private static List<String> list = new ArrayList<String>();
*? (02) 使用時CopyOnWriteArrayList为严,不會產生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) {
? ? ? ? // 同時啟動兩個線程對list進行操作例诀!
? ? ? ? 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,每添加一個數之后裁着,就通過printAll()遍歷整個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,每添加一個數之后拱她,就通過printAll()遍歷整個list
? ? */
? ? private static class ThreadTwo extends Thread {
? ? ? ? public void run() {
? ? ? ? ? ? int i = 10;
? ? ? ? ? ? while (i<16) {
? ? ? ? ? ? ? ? list.add(String.valueOf(i));
? ? ? ? ? ? ? ? printAll();
? ? ? ? ? ? ? ? i++;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
運行結果:
運行該代碼二驰,拋出異常java.util.ConcurrentModificationException!即秉沼,產生fail-fast事件桶雀!
結果說明:
(01) FastFailTest中通過 new ThreadOne().start() 和 new ThreadTwo().start() 同時啟動兩個線程去操作list。
?ThreadOne線程:向list中依次添加0,1,2,3,4,5唬复。每添加一個數之后矗积,就通過printAll()遍歷整個list。
?ThreadTwo線程:向list中依次添加10,11,12,13,14,15敞咧。每添加一個數之后棘捣,就通過printAll()遍歷整個list。
(02) 當某一個線程遍歷list的過程中休建,list的內容被另外一個線程所改變了乍恐;就會拋出ConcurrentModificationException異常,產生fail-fast事件测砂。
3 fail-fast解決辦法
fail-fast機制茵烈,是一種錯誤檢測機制。它只能被用來檢測錯誤砌些,因為JDK并不保證fail-fast機制一定會發(fā)生呜投。若在多線程環(huán)境下使用fail-fast機制的集合,建議使用“java.util.concurrent包下的類”去取代“java.util包下的類”。
所以仑荐,本例中只需要將ArrayList替換成java.util.concurrent包下對應的類即可雕拼。
即,將代碼
privatestaticList list =newArrayList();
替換為
privatestaticList list =newCopyOnWriteArrayList();
則可以解決該辦法释漆。
4 fail-fast原理
產生fail-fast事件悲没,是通過拋出ConcurrentModificationException異常來觸發(fā)的。
那么男图,ArrayList是如何拋出ConcurrentModificationException異常的呢?
我們知道示姿,ConcurrentModificationException是在操作Iterator時拋出的異常。我們先看看Iterator的源碼逊笆。ArrayList的Iterator是在父類AbstractList.java中實現的栈戳。代碼如下:
package java.util;
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
? ? ...
? ? // AbstractList中唯一的屬性
? ? // 用來記錄List修改的次數:每修改一次(添加/刪除等操作),將modCount+1
? ? protected transient int modCount = 0;
? ? // 返回List對應迭代器难裆。實際上子檀,是返回Itr對象。
? ? public Iterator<E> iterator() {
? ? ? ? return new Itr();
? ? }
? ? // Itr是Iterator(迭代器)的實現類
? ? private class Itr implements Iterator<E> {
? ? ? ? int cursor = 0;
? ? ? ? int lastRet = -1;
? ? ? ? // 修改數的記錄值乃戈。
? ? ? ? // 每次新建Itr()對象時褂痰,都會保存新建該對象時對應的modCount;
? ? ? ? // 以后每次遍歷List中的元素的時候症虑,都會比較expectedModCount和modCount是否相等缩歪;
? ? ? ? // 若不相等,則拋出ConcurrentModificationException異常谍憔,產生fail-fast事件匪蝙。
? ? ? ? int expectedModCount = modCount;
? ? ? ? public boolean hasNext() {
? ? ? ? ? ? return cursor != size();
? ? ? ? }
? ? ? ? public E next() {
? ? ? ? ? ? // 獲取下一個元素之前,都會判斷“新建Itr對象時保存的modCount”和“當前的modCount”是否相等习贫;
? ? ? ? ? ? // 若不相等逛球,則拋出ConcurrentModificationException異常,產生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ā)現在調用 next() 和 remove()時,都會執(zhí)行 checkForComodification()祟身。若 “modCount 不等于 expectedModCount”屋厘,則拋出ConcurrentModificationException異常,產生fail-fast事件月而。
要搞明白 fail-fast機制汗洒,我們就要需要理解什么時候“modCount 不等于 expectedModCount”!
從Itr類中父款,我們知道 expectedModCount 在創(chuàng)建Itr對象時溢谤,被賦值為 modCount瞻凤。通過Itr,我們知道:expectedModCount不可能被修改為不等于 modCount世杀。所以阀参,需要考證的就是modCount何時會被修改。
接下來瞻坝,我們查看ArrayList的源碼蛛壳,來看看modCount是如何被修改的。
package java.util;
public class ArrayList<E> extends AbstractList<E>
? ? ? ? implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
? ? ...
? ? // list中容量變化時所刀,對應的同步函數
? ? 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);
? ? ? ? }
? ? }
? ? // 添加元素到隊列最后
? ? 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ā)現:無論是add()、remove()浮创,還是clear()忧吟,只要涉及到修改集合中的元素個數時,都會改變modCount的值斩披。
接下來溜族,我們再系統(tǒng)的梳理一下fail-fast是怎么產生的。步驟如下:
(01)?新建了一個ArrayList垦沉,名稱為arrayList煌抒。
(02)?向arrayList中添加內容。
(03)?新建一個“線程a”厕倍,并在“線程a”中通過Iterator反復的讀取arrayList的值寡壮。
(04)?新建一個“線程b”,在“線程b”中刪除arrayList中的一個“節(jié)點A”绑青。
(05) 這時,就會產生有趣的事件了屋群。
在某一時刻闸婴,“線程a”創(chuàng)建了arrayList的Iterator。此時“節(jié)點A”仍然存在于arrayList中芍躏,創(chuàng)建arrayList時邪乍,expectedModCount = modCount(假設它們此時的值為N)。
在“線程a”在遍歷arrayList過程中的某一時刻对竣,“線程b”執(zhí)行了庇楞,并且“線程b”刪除了arrayList中的“節(jié)點A”》裎常“線程b”執(zhí)行remove()進行刪除操作時吕晌,在remove()中執(zhí)行了“modCount++”,此時modCount變成了N+1临燃!
“線程a”接著遍歷睛驳,當它執(zhí)行到next()函數時烙心,調用checkForComodification()比較“expectedModCount”和“modCount”的大小乏沸;而“expectedModCount=N”淫茵,“modCount=N+1”,這樣,便拋出ConcurrentModificationException異常蹬跃,產生fail-fast事件匙瘪。
至此,我們就完全了解了fail-fast是如何產生的蝶缀!
即丹喻,當多個線程對同一個集合進行操作的時候,某線程訪問集合的過程中扼劈,該集合的內容被其他線程所改變(即其它線程通過add驻啤、remove、clear等方法荐吵,改變了modCount的值)骑冗;這時,就會拋出ConcurrentModificationException異常先煎,產生fail-fast事件贼涩。
5 解決fail-fast的原理
上面,說明了“解決fail-fast機制的辦法”薯蝎,也知道了“fail-fast產生的根本原因”遥倦。接下來,我們再進一步談談java.util.concurrent包中是如何解決fail-fast事件的占锯。
還是以和ArrayList對應的CopyOnWriteArrayList進行說明袒哥。我們先看看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 {
? ? ...
? ? // 返回集合對應的迭代器
? ? public Iterator<E> iterator() {
? ? ? ? return new 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時,將集合中的元素保存到一個新的拷貝數組中消略。
? ? ? ? ? ? // 這樣堡称,當原始集合的數據改變,拷貝數據中的值也不會變化艺演。
? ? ? ? ? ? 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沒有繼承于AbstractList胎撤,它僅僅只是實現了List接口晓殊。
(02) ArrayList的iterator()函數返回的Iterator是在AbstractList中實現的;而CopyOnWriteArrayList是自己實現Iterator伤提。
(03) ArrayList的Iterator實現類中調用next()時巫俺,會“調用checkForComodification()比較‘expectedModCount’和‘modCount’的大小”;但是肿男,CopyOnWriteArrayList的Iterator實現類中识藤,沒有所謂的checkForComodification()砚著,更不會拋出ConcurrentModificationException異常!
感興趣的朋友可以加群一起閑聊qq群947405150痴昧, 加群947405150 一起探討技術交流;隆!不懂的可以問下群里管理赶撰!