Java結合--ArrayList出現同步問題的原因

來源:互聯網
上載者:User

標籤:rev   tin   bar   run   return   判斷   exception   done   技術   

1 fail-fast簡介

fail-fast 機制是java集合(Collection)中的一種錯誤機制。當多個線程對同一個集合的內容進行操作時,就可能會產生fail-fast事件。
例如:當某一個線程A通過iterator去遍曆某集合的過程中,若該集合的內容被其他線程所改變了;那麼線程A訪問集合時,就會拋出ConcurrentModificationException異常,產生fail-fast事件。

在詳細介紹fail-fast機制的原理之前,先通過一個樣本來認識fail-fast。

  

2 fail-fast樣本

範例程式碼:(FastFailTest.java)

 1 import java.util.*; 2 import java.util.concurrent.*; 3  4 /* 5  * @desc java集合中Fast-Fail的測試程式。 6  * 7  *   fast-fail事件產生的條件:當多個線程對Collection進行操作時,若其中某一個線程通過iterator去遍曆集合時,該集合的內容被其他線程所改變;則會拋出ConcurrentModificationException異常。 8  *   fast-fail解決辦法:通過util.concurrent集合包下的相應類去處理,則不會產生fast-fail事件。 9  *10  *   本例中,分別測試ArrayList和CopyOnWriteArrayList這兩種情況。ArrayList會產生fast-fail事件,而CopyOnWriteArrayList不會產生fast-fail事件。11  *   (01) 使用ArrayList時,會產生fast-fail事件,拋出ConcurrentModificationException異常;定義如下:12  *            private static List<String> list = new ArrayList<String>();13  *   (02) 使用時CopyOnWriteArrayList,不會產生fast-fail事件;定義如下:14  *            private static List<String> list = new CopyOnWriteArrayList<String>();15  *16  * @author skywang17  */18 public class FastFailTest {19 20     private static List<String> list = new ArrayList<String>();21     //private static List<String> list = new CopyOnWriteArrayList<String>();22     public static void main(String[] args) {23     24         // 同時啟動兩個線程對list進行操作!25         new ThreadOne().start();26         new ThreadTwo().start();27     }28 29     private static void printAll() {30         System.out.println("");31 32         String value = null;33         Iterator iter = list.iterator();34         while(iter.hasNext()) {35             value = (String)iter.next();36             System.out.print(value+", ");37         }38     }39 40     /**41      * 向list中依次添加0,1,2,3,4,5,每添加一個數之後,就通過printAll()遍曆整個list42      */43     private static class ThreadOne extends Thread {44         public void run() {45             int i = 0;46             while (i<6) {47                 list.add(String.valueOf(i));48                 printAll();49                 i++;50             }51         }52     }53 54     /**55      * 向list中依次添加10,11,12,13,14,15,每添加一個數之後,就通過printAll()遍曆整個list56      */57     private static class ThreadTwo extends Thread {58         public void run() {59             int i = 10;60             while (i<16) {61                 list.add(String.valueOf(i));62                 printAll();63                 i++;64             }65         }66     }67 68 }

運行結果:
運行該代碼,拋出異常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機制一定會發生。若在多線程環境下使用fail-fast機制的集合,建議使用“java.util.concurrent包下的類”去取代“java.util包下的類”。
所以,本例中只需要將ArrayList替換成java.util.concurrent包下對應的類即可。
即,將代碼

private static List<String> list = new ArrayList<String>();

替換為

private static List<String> list = new CopyOnWriteArrayList<String>();

則可以解決該辦法。

 

4 fail-fast原理

產生fail-fast事件,是通過拋出ConcurrentModificationException異常來觸發的。
那麼,ArrayList是如何拋出ConcurrentModificationException異常的呢?

我們知道,ConcurrentModificationException是在操作Iterator時拋出的異常。我們先看看Iterator的源碼。ArrayList的Iterator是在父類AbstractList.java中實現的。代碼如下: 

 1 package java.util; 2  3 public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { 4  5     ... 6  7     // AbstractList中唯一的屬性 8     // 用來記錄List修改的次數:每修改一次(添加/刪除等操作),將modCount+1 9     protected transient int modCount = 0;10 11     // 返回List對應迭代器。實際上,是返回Itr對象。12     public Iterator<E> iterator() {13         return new Itr();14     }15 16     // Itr是Iterator(迭代器)的實作類別17     private class Itr implements Iterator<E> {18         int cursor = 0;19 20         int lastRet = -1;21 22         // 修改數的記錄值。23         // 每次建立Itr()對象時,都會儲存建立該對象時對應的modCount;24         // 以後每次遍曆List中的元素的時候,都會比較expectedModCount和modCount是否相等;25         // 若不相等,則拋出ConcurrentModificationException異常,產生fail-fast事件。26         int expectedModCount = modCount;27 28         public boolean hasNext() {29             return cursor != size();30         }31 32         public E next() {33             // 擷取下一個元素之前,都會判斷“建立Itr對象時儲存的modCount”和“當前的modCount”是否相等;34             // 若不相等,則拋出ConcurrentModificationException異常,產生fail-fast事件。35             checkForComodification();36             try {37                 E next = get(cursor);38                 lastRet = cursor++;39                 return next;40             } catch (IndexOutOfBoundsException e) {41                 checkForComodification();42                 throw new NoSuchElementException();43             }44         }45 46         public void remove() {47             if (lastRet == -1)48                 throw new IllegalStateException();49             checkForComodification();50 51             try {52                 AbstractList.this.remove(lastRet);53                 if (lastRet < cursor)54                     cursor--;55                 lastRet = -1;56                 expectedModCount = modCount;57             } catch (IndexOutOfBoundsException e) {58                 throw new ConcurrentModificationException();59             }60         }61 62         final void checkForComodification() {63             if (modCount != expectedModCount)64                 throw new ConcurrentModificationException();65         }66     }67 68     ...69 }

從中,我們可以發現在調用 next() 和 remove()時,都會執行 checkForComodification()。若 “modCount 不等於 expectedModCount”,則拋出ConcurrentModificationException異常,產生fail-fast事件。

要搞明白 fail-fast機制,我們就要需要理解什麼時候“modCount 不等於 expectedModCount”!
從Itr類中,我們知道 expectedModCount 在建立Itr對象時,被賦值為 modCount。通過Itr,我們知道:expectedModCount不可能被修改為不等於 modCount。所以,需要考證的就是modCount何時會被修改。

接下來,我們查看ArrayList的源碼,來看看modCount是如何被修改的

  1 package java.util;  2   3 public class ArrayList<E> extends AbstractList<E>  4         implements List<E>, RandomAccess, Cloneable, java.io.Serializable  5 {  6   7     ...  8   9     // list中容量變化時,對應的同步函數 10     public void ensureCapacity(int minCapacity) { 11         modCount++; 12         int oldCapacity = elementData.length; 13         if (minCapacity > oldCapacity) { 14             Object oldData[] = elementData; 15             int newCapacity = (oldCapacity * 3)/2 + 1; 16             if (newCapacity < minCapacity) 17                 newCapacity = minCapacity; 18             // minCapacity is usually close to size, so this is a win: 19             elementData = Arrays.copyOf(elementData, newCapacity); 20         } 21     } 22  23  24     // 添加元素到隊列最後 25     public boolean add(E e) { 26         // 修改modCount 27         ensureCapacity(size + 1);  // Increments modCount!! 28         elementData[size++] = e; 29         return true; 30     } 31  32  33     // 添加元素到指定的位置 34     public void add(int index, E element) { 35         if (index > size || index < 0) 36             throw new IndexOutOfBoundsException( 37             "Index: "+index+", Size: "+size); 38  39         // 修改modCount 40         ensureCapacity(size+1);  // Increments modCount!! 41         System.arraycopy(elementData, index, elementData, index + 1, 42              size - index); 43         elementData[index] = element; 44         size++; 45     } 46  47     // 添加集合 48     public boolean addAll(Collection<? extends E> c) { 49         Object[] a = c.toArray(); 50         int numNew = a.length; 51         // 修改modCount 52         ensureCapacity(size + numNew);  // Increments modCount 53         System.arraycopy(a, 0, elementData, size, numNew); 54         size += numNew; 55         return numNew != 0; 56     } 57     58  59     // 刪除指定位置的元素  60     public E remove(int index) { 61         RangeCheck(index); 62  63         // 修改modCount 64         modCount++; 65         E oldValue = (E) elementData[index]; 66  67         int numMoved = size - index - 1; 68         if (numMoved > 0) 69             System.arraycopy(elementData, index+1, elementData, index, numMoved); 70         elementData[--size] = null; // Let gc do its work 71  72         return oldValue; 73     } 74  75  76     // 快速刪除指定位置的元素  77     private void fastRemove(int index) { 78  79         // 修改modCount 80         modCount++; 81         int numMoved = size - index - 1; 82         if (numMoved > 0) 83             System.arraycopy(elementData, index+1, elementData, index, 84                              numMoved); 85         elementData[--size] = null; // Let gc do its work 86     } 87  88     // 清空集合 89     public void clear() { 90         // 修改modCount 91         modCount++; 92  93         // Let gc do its work 94         for (int i = 0; i < size; i++) 95             elementData[i] = null; 96  97         size = 0; 98     } 99 100     ...101 }

從中,我們發現:無論是add()、remove(),還是clear(),只要涉及到修改集合中的元素個數時,都會改變modCount的值。

接下來,我們再系統的梳理一下fail-fast是怎麼產生的。步驟如下:
(01) 建立了一個ArrayList,名稱為arrayList。
(02) 向arrayList中新增內容。
(03) 建立一個“線程a”,並在“線程a”中通過Iterator反覆的讀取arrayList的值。
(04) 建立一個“線程b”,在“線程b”中刪除arrayList中的一個“節點A”。
(05) 這時,就會產生有趣的事件了。
       在某一時刻,“線程a”建立了arrayList的Iterator。此時“節點A”仍然存在於arrayList中,建立arrayList時,expectedModCount = modCount(假設它們此時的值為N)。
       在“線程a”在遍曆arrayList過程中的某一時刻,“線程b”執行了,並且“線程b”刪除了arrayList中的“節點A”。“線程b”執行remove()進行刪除操作時,在remove()中執行了“modCount++”,此時modCount變成了N+1!
“線程a”接著遍曆,當它執行到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; 2 import java.util.*; 3 import java.util.concurrent.locks.*; 4 import sun.misc.Unsafe; 5  6 public class CopyOnWriteArrayList<E> 7     implements List<E>, RandomAccess, Cloneable, java.io.Serializable { 8  9     ...10 11     // 返回集合對應的迭代器12     public Iterator<E> iterator() {13         return new COWIterator<E>(getArray(), 0);14     }15 16     ...17    18     private static class COWIterator<E> implements ListIterator<E> {19         private final Object[] snapshot;20 21         private int cursor;22 23         private COWIterator(Object[] elements, int initialCursor) {24             cursor = initialCursor;25             
          //CopyOnWriteArrayList的add、set、remove等會改變原數組的方法中,都是先copy一份原來的array,
          //再在copy數組上進行add、set、remove操作,這就才不影響COWIterator那份數組27 snapshot = elements;28 }29 30 public boolean hasNext() {31 return cursor < snapshot.length;32 }33 34 public boolean hasPrevious() {35 return cursor > 0;36 }37 38 public E next() {39 if (! hasNext())40 throw new NoSuchElementException();41 return (E) snapshot[cursor++];42 }43 44 public E previous() {45 if (! hasPrevious())46 throw new NoSuchElementException();47 return (E) snapshot[--cursor];48 }49 50 public int nextIndex() {51 return cursor;52 }53 54 public int previousIndex() {55 return cursor-1;56 }57 58 public void remove() {59 throw new UnsupportedOperationException();60 }61 62 public void set(E e) {63 throw new UnsupportedOperationException();64 }65 66 public void add(E e) {67 throw new UnsupportedOperationException();68 }69 }70 71 ...72 73 }

從中,我們可以看出:

(01) 和ArrayList繼承於AbstractList不同,CopyOnWriteArrayList沒有繼承於AbstractList,它僅僅只是實現了List介面。
(02) ArrayList的iterator()函數返回的Iterator是在AbstractList中實現的;而CopyOnWriteArrayList是自己實現Iterator。
(03) ArrayList的Iterator實作類別中調用next()時,會“調用checkForComodification()比較‘expectedModCount’和‘modCount’的大小”;但是,CopyOnWriteArrayList的Iterator實作類別中,沒有所謂的checkForComodification(),更不會拋出ConcurrentModificationException異常! 

 轉載: http://www.cnblogs.com/skywang12345/p/3308762.html

Java結合--ArrayList出現同步問題的原因

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.