Java并发--ConcurrentModificationException(并发修改异常)异常缘由和解决方法

  在前面一篇文章中提到,对Vector、ArrayList在迭代的时候若是同时对其进行修改就会抛出java.util.ConcurrentModificationException异常。下面咱们就来讨论如下这个异常出现的缘由以及解决办法。html

  如下是本文目录大纲:java

  一.ConcurrentModificationException异常出现的缘由安全

  二.在单线程环境下的解决办法多线程

  三.在多线程环境下的解决方法并发

  转载原文连接:http://www.cnblogs.com/dolphin0520/p/3933551.htmlthis

一.ConcurrentModificationException异常出现的缘由

  先看下面这段代码:spa

 1 public class Test {  2     public static void main(String[] args) {  3         ArrayList<Integer> list = new ArrayList<Integer>();  4         list.add(2);  5         Iterator<Integer> iterator = list.iterator();  6         while(iterator.hasNext()){  7             Integer integer = iterator.next();  8             if(integer==2)  9  list.remove(integer); 10  } 11  } 12 }

运行结果:.net

  

  从异常信息能够发现,异常出如今checkForComodification()方法中。线程

  咱们不忙看checkForComodification()方法的具体实现,咱们先根据程序的代码一步一步看ArrayList源码的实现:code

  首先看ArrayList的iterator()方法的具体实现,查看源码发如今ArrayList的源码中并无iterator()这个方法,那么很显然这个方法应该是其父类或者实现的接口中的方法,咱们在其父类AbstractList中找到了iterator()方法的具体实现,下面是其实现代码:

public Iterator<E> iterator() { return new Itr(); }

从这段代码能够看出返回的是一个指向Itr类型对象的引用,咱们接着看Itr的具体实现,在AbstractList类中找到了Itr类的具体实现,它是AbstractList的一个成员内部类,下面这段代码是Itr类的全部实现:

 1 private class Itr implements Iterator<E> {  2     int cursor = 0;  3     int lastRet = -1;  4     int expectedModCount = modCount;  5     public boolean hasNext() {  6            return cursor != size();  7  }  8     public E next() {  9  checkForComodification(); 10         try { 11         E next = get(cursor); 12         lastRet = cursor++; 13         return next; 14         } catch (IndexOutOfBoundsException e) { 15  checkForComodification(); 16         throw new NoSuchElementException(); 17  } 18  } 19     public void remove() { 20         if (lastRet == -1) 21         throw new IllegalStateException(); 22  checkForComodification(); 23  
24         try { 25         AbstractList.this.remove(lastRet); 26         if (lastRet < cursor) 27             cursor--; 28         lastRet = -1; 29         expectedModCount = modCount; 30         } catch (IndexOutOfBoundsException e) { 31         throw new ConcurrentModificationException(); 32  } 33  } 34  
35     final void checkForComodification() { 36         if (modCount != expectedModCount) 37         throw new ConcurrentModificationException(); 38  } 39 }

首先咱们看一下它的几个成员变量:

  cursor:表示下一个要访问的元素的索引,从next()方法的具体实现就可看出

  lastRet:表示上一个访问的元素的索引

  expectedModCount:表示对ArrayList修改次数的指望值,它的初始值为modCount。

  modCount是AbstractList类中的一个成员变量

protected transient int modCount = 0;

该值表示对List的修改次数,查看ArrayList的add()和remove()方法就能够发现,每次调用add()方法或者remove()方法就会对modCount进行加1操做。

  好了,到这里咱们再看看上面的程序:

  当调用list.iterator()返回一个Iterator以后,经过Iterator的hashNext()方法判断是否还有元素未被访问,咱们看一下hasNext()方法,hashNext()方法的实现很简单:

public boolean hasNext() { return cursor != size(); }

若是下一个访问的元素下标不等于ArrayList的大小,就表示有元素须要访问,这个很容易理解,若是下一个访问元素的下标等于ArrayList的大小,则确定到达末尾了。

  而后经过Iterator的next()方法获取到下标为0的元素,咱们看一下next()方法的具体实现:

public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }

这里是很是关键的地方:首先在next()方法中会调用checkForComodification()方法,而后根据cursor的值获取到元素,接着将cursor的值赋给lastRet,并对cursor的值进行加1操做。初始时,cursor为0,lastRet为-1,那么调用一次以后,cursor的值为1,lastRet的值为0。注意此时,modCount为0,expectedModCount也为0。

  接着往下看,程序中判断当前元素的值是否为2,若为2,则调用list.remove()方法来删除该元素。

  咱们看一下在ArrayList中的remove()方法作了什么:

public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } private void fastRemove(int index) { 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
}

经过remove方法删除元素最终是调用的fastRemove()方法,在fastRemove()方法中,首先对modCount进行加1操做(由于对集合修改了一次),而后接下来就是删除元素的操做,最后将size进行减1操做,并将引用置为null以方便垃圾收集器进行回收工做。

  那么注意此时各个变量的值:对于iterator,其expectedModCount为0,cursor的值为1,lastRet的值为0。

  对于list,其modCount为1,size为0。

  接着看程序代码,执行完删除操做后,继续while循环,调用hasNext方法()判断,因为此时cursor为1,而size为0,那么返回true,因此继续执行while循环,而后继续调用iterator的next()方法:

  注意,此时要注意next()方法中的第一句:checkForComodification()。

  在checkForComodification方法中进行的操做是:

final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }

若是modCount不等于expectedModCount,则抛出ConcurrentModificationException异常。

  很显然,此时modCount为1,而expectedModCount为0,所以程序就抛出了ConcurrentModificationException异常。

  到这里,想必你们应该明白为什么上述代码会抛出ConcurrentModificationException异常了。

  关键点就在于:调用list.remove()方法致使modCount和expectedModCount的值不一致。

  注意,像使用for-each进行迭代实际上也会出现这种问题。

二.在单线程环境下的解决办法

  既然知道缘由了,那么如何解决呢?

  其实很简单,细心的朋友可能发如今Itr类中也给出了一个remove()方法:

 1 public void remove() {  2     if (lastRet == -1)  3     throw new IllegalStateException();  4  checkForComodification();  5  
 6     try {  7     AbstractList.this.remove(lastRet);  8     if (lastRet < cursor)  9         cursor--; 10     lastRet = -1; 11     expectedModCount = modCount; 12     } catch (IndexOutOfBoundsException e) { 13     throw new ConcurrentModificationException(); 14  } 15 }

在这个方法中,删除元素实际上调用的就是list.remove()方法,可是它多了一个操做:

expectedModCount = modCount;

所以,在迭代器中若是要删除元素的话,须要调用Itr类的remove方法。

  将上述代码改成下面这样就不会报错了:

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) iterator.remove(); //注意这个地方
 } } }

三.在多线程环境下的解决方法

  上面的解决办法在单线程环境下适用,可是在多线程下适用吗?看下面一个例子:

 1 public class Test {  2     static ArrayList<Integer> list = new ArrayList<Integer>();  3     public static void main(String[] args) {  4         list.add(1);  5         list.add(2);  6         list.add(3);  7         list.add(4);  8         list.add(5);  9         Thread thread1 = new Thread(){ 10             public void run() { 11                 Iterator<Integer> iterator = list.iterator(); 12                 while(iterator.hasNext()){ 13                     Integer integer = iterator.next(); 14  System.out.println(integer); 15                     try { 16                         Thread.sleep(100); 17                     } catch (InterruptedException e) { 18  e.printStackTrace(); 19  } 20  } 21  }; 22  }; 23         Thread thread2 = new Thread(){ 24             public void run() { 25                 Iterator<Integer> iterator = list.iterator(); 26                 while(iterator.hasNext()){ 27                     Integer integer = iterator.next(); 28                     if(integer==2) 29  iterator.remove(); 30  } 31  }; 32  }; 33  thread1.start(); 34  thread2.start(); 35  } 36 }

运行结果:

  

  有可能有朋友说ArrayList是非线程安全的容器,换成Vector就没问题了,实际上换成Vector仍是会出现这种错误。

  缘由在于,虽然Vector的方法采用了synchronized进行了同步,可是因为Vector是继承的AbstarctList,所以经过Iterator来访问容器的话,事实上是不须要获取锁就能够访问。那么显然,因为使用iterator对容器进行访问不须要获取锁,在多线程中就会形成当一个线程删除了元素,因为modCount是AbstarctList的成员变量,所以可能会致使在其余线程中modCount和expectedModCount值不等。

  就好比上面的代码中,很显然iterator是线程私有的,

  初始时,线程1和线程2中的modCount、expectedModCount都为0,

  当线程2经过iterator.remove()删除元素时,会修改modCount值为1,而且会修改线程2中的expectedModCount的值为1,

  而此时线程1中的expectedModCount值为0,虽然modCount不是volatile变量,不保证线程1必定看获得线程2修改后的modCount的值,可是也有可能看获得线程2对modCount的修改,这样就有可能致使线程1中比较expectedModCount和modCount不等,而抛出异常。

  所以通常有2种解决办法:

  1)在使用iterator迭代的时候使用synchronized或者Lock进行同步;

  2)使用并发容器CopyOnWriteArrayList代替ArrayList和Vector。

  关于并发容器的内容将在下一篇文章中讲述。

  参考资料:

  http://blog.csdn.net/izard999/article/details/6708738

  http://www.2cto.com/kf/201403/286536.html

相关文章
相关标签/搜索