关于List的ConcurrentModificationException
对ArrayList的操作我们可以通过索引象来访问,也可以通过Iterator来访问,只要不对ArrayList结构上进行修改都不会造成ConcurrentModificationException,单独用索引对ArrayList进行修改也不会造成该问题,造成该问题主要是在索引和Iterator混用。可以通过JDK的源码来说明该问题。
首先看下AbstractList的Iterator内的代码:
/** * 在Iterator的内部有个expectedModCount 变量, * 该变量每次初始化*Iterator的时候等于ArrayList的modCount,modCount记录了对ArrayList的结构修改次数, * 在通过Iterator对ArrayList进行结构的修改的时候都会将expectedModCount 与modCount同步, * 但是如果在通过Iterator访问的时候同时又通过索引的方式去修改ArrayList的结构的话, * 由于通过索引的方式只会修改modCount不会同步修改expectedModCount 就会导致 * modCount和expectedModCount 不相等就会抛ConcurrentModificationException, * 这也就是Iterator的fail-fast,快速失效的。所以只要采取一种方式操作ArrayList就不会出问题, * 当然ArrayList不是线程安全的,此处不讨论对线程问题。 */ int expectedModCount = modCount; public E next() { checkForComodification();//判断modeCount与expectedModCount 是否相等,如果不相等就抛异常 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();//同样去判断modeCount与expectedModCount 是否相等 try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount;//此处修改ArrayList的结构,所以要将expectedModCount 于modCount同步,主要是AbstractList.this.remove(lastRet);的remove方法中将modCount++了,导致了modCount与expectedModCount 不相等了。 } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } //判断modCount 与expectedModCount是否相等,如果不相等就抛ConcurrentModificationException异常 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
故我的结论是:对ArrayList的操作采用一种遍历方式,要么索引,要么Iterator别混用即可。
/* Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。 所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性 */
作者:fenglie
专注于JAVAEE开发,热爱开源项目
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。