LinkedList 跑出的ConcurrentModificationException異常

項目中,使用LinkedList時,後臺拋出了ConcurrentModificationException異常

看源碼發現問題所在,分析如下:

 1.異常最外層的方法(直接拋出異常的方法):

  final void checkForComodification()
    {
      if (LinkedList.this.modCount != this.expectedModCount) {
        throw new ConcurrentModificationException();
      }
    }
  }
modCount:LinkedList對象的字段,add(),remove()操作均會對該字段執行++.

expectedModCount:迭代器iterator對象的字段,同樣,add(),remove操作會自增該字段值.


2.拋出異常調用的業務方法模擬:

  <pre name="code" class="java">public class Test {
    public static void main(String[] args)  {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(2);
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            Integer integer = iterator.next();
            if(integer==2)
                list.remove(integer);
        }
    }
}

list對象執行 
list.add(2);
後,其modCount ==1,之後生成iterator 對象,iterator的 expectedModCount==1,此時,這二個值是一致的。

當執行<span style="font-family: Verdana, Arial, Helvetica, sans-serif;">list.remove(integer);</span><span style="font-family: Verdana, Arial, Helvetica, sans-serif;">後,注意這個時候,</span><span style="font-family: Verdana, Arial, Helvetica, sans-serif;">modCount ==2,而expectedModCount==1</span><span style="font-family: Verdana, Arial, Helvetica, sans-serif;font-size:18px; line-height: 28px;"></span>

在往下,按正常思維,再次執行

while(iterator.hasNext())時,直覺是我就加了一個對象進來,這個時候,應該沒有下一個元素了,所以這裏不會進來了..

問題就在這裏,因爲剛纔我們調用的是 list.remove(integer);
執行後,對iterator內部是沒有影響的,所以再次執行

while(iterator.hasNext())
後,iterator內部判斷還沒有達到size,所以還是會繼續執行,然後執行
iterator.next();
此時,在next()方法內部會先執行
checkForComodification();
發現modCount 和expectedModCount 不一致,拋出異常。

說到這裏大家已經明白了吧

解決方法如下:

public static void main(String[] args)  {
	        LinkedList<Integer> list = new LinkedList<Integer>();
	        list.add(2);
	        Iterator<Integer> iterator = list.iterator();
	        while(iterator.hasNext()){
	            Integer integer = iterator.next();
	            if(integer==2){
	            	iterator.remove();
	            }
	        }
	    }

歡迎交流,轉載請註明出處:http://blog.csdn.net/smithdoudou88/article/details/48131107


發佈了112 篇原創文章 · 獲贊 14 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章