首页 > 技术文章 > 关于List的ConcurrentModificationException

bojuetech 2016-12-15 11:48 原文

对ArrayList的操作我们可以通过索引象来访问,也可以通过Iterator来访问,只要不对ArrayList结构上进行修改都不会造成ConcurrentModificationException,单独用索引对ArrayList进行修改也不会造成该问题,造成该问题主要是在索引和Iterator混用。可以通过JDK的源码来说明该问题。

   首先看下AbstractList的Iterator内的代码:

 

Java代码  收藏代码
  1. /** 
  2. *在Iterator的内部有个expectedModCount 变量, 
  3. *该变量每次初始化*Iterator的时候等于ArrayList的modCount,modCount记录了对ArrayList的结构修改次数, 
  4. *在通过Iterator对ArrayList进行结构的修改的时候都会将expectedModCount 与modCount同步, 
  5. *但是如果在通过Iterator访问的时候同时又通过索引的方式去修改ArrayList的结构的话, 
  6. *由于通过索引的方式只会修改modCount不会同步修改expectedModCount 就会导致 
  7. *modCount和expectedModCount 不相等就会抛ConcurrentModificationException, 
  8. *这也就是Iterator的fail-fast,快速失效的。所以只要采取一种方式操作ArrayList就不会出问题, 
  9. *当然ArrayList不是线程安全的,此处不讨论对线程问题。 
  10. */  
  11. int expectedModCount = modCount;  
  12. public E next() {  
  13.             checkForComodification();//判断modeCount与expectedModCount 是否相等,如果不相等就抛异常  
  14.         try {  
  15.         E next = get(cursor);  
  16.         lastRet = cursor++;  
  17.         return next;  
  18.         } catch (IndexOutOfBoundsException e) {  
  19.         checkForComodification();  
  20.         throw new NoSuchElementException();  
  21.         }  
  22. }  
  23.   
  24. public void remove() {  
  25.      if (lastRet == -1)  
  26.         throw new IllegalStateException();  
  27.           checkForComodification();//同样去判断modeCount与expectedModCount 是否相等  
  28.   
  29.       try {  
  30.         AbstractList.this.remove(lastRet);  
  31.         if (lastRet < cursor)  
  32.             cursor--;  
  33.         lastRet = -1;  
  34.         expectedModCount = modCount;//此处修改ArrayList的结构,所以要将expectedModCount 于modCount同步,主要是AbstractList.this.remove(lastRet);的remove方法中将modCount++了,导致了modCount与expectedModCount 不相等了。  
  35.        } catch (IndexOutOfBoundsException e) {  
  36.         throw new ConcurrentModificationException();  
  37.        }  
  38. }  
  39.   
  40. //判断modCount 与expectedModCount是否相等,如果不相等就抛ConcurrentModificationException异常  
  41. final void checkForComodification() {  
  42.      if (modCount != expectedModCount)  
  43.           throw new ConcurrentModificationException();  
  44. }  

 

故我的结论是:对ArrayList的操作采用一种遍历方式,要么索引,要么Iterator别混用即可。

下面是网上看见别人的解释:写道

Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性

推荐阅读