工作中碰到个ConcurrentModificationException。ConcurrentModificationException,它是在使用迭代器遍历集合对象时修改集合对象造成的(并发修改)异常。实际上,Java的集合框架是迭代器设计模式的一个很好的实现。
代码如下:
List list = ...; for(Iterator iter = list.iterator(); iter.hasNext();) { Object obj = iter.next(); ... if(***) { list.remove(obj); } }
在执行了remove方法之后,再去执行循环,iter.next()的时候,报java.util.ConcurrentModificationException(当然,如果remove的是最后一条,就不会再去执行next()操作了)
下面来看一下源码
public interface Iterator<E> { boolean hasNext(); E next(); void remove(); }
public interface Collection<E> extends Iterable<E> { ... Iterator<E> iterator(); boolean add(E o); boolean remove(Object o); ... }
这里有两个remove方法
接下来来看看AbstractList
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { //AbstractCollection和List都继承了Collection protected transient int modCount = 0; private class Itr implements Iterator<E> { //内部类Itr int cursor = 0; int lastRet = -1; int expectedModCount = modCount; public boolean hasNext() { return cursor != size(); } public E next() { checkForComodification(); //特别注意这个方法 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(); try { AbstractList.this.remove(lastRet); //执行remove对象的操作 if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; //重新设置了expectedModCount的值,避免了ConcurrentModificationException的产生 } catch(IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException throw new ConcurrentModificationException(); } } }
remove(Object o)在ArrayList中实现如下:
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++; //只增加了modCount .... }
所以,产生ConcurrentModificationException的原因就是:执行remove(Object o)方法之后,modCount和expectedModCount不相等了。然后当代码执行到next()方法时,判断了checkForComodification(),发现两个数值不等,就抛出了该Exception。
其实这是集合迭代中的一种“快速失败”机制,这种机制提供迭代过程中集合的安全性。
要避免这个Exception,就应该使用remove()方法。故在遍历的过程中,边遍历边删除时可以使用iterator进行。
这里我们就不看add(Object o)方法了,也是同样的原因,但没有对应的add()方法。一般嘛,就另建一个List了。
Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。
使用Iterator边遍历边操作的总结:
1、key不能修改,只能删除,也即只能删除key-value对,不能新增和修改key-value
2、value值,可以被修改或删除(同key一起)
示例说明:
package com.dxz.concurrent.hashmap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
// ConcurrentHashMap
Map<String, String> myMap = new ConcurrentHashMap<String, String>();
myMap.put("1", "1");
myMap.put("2", "1");
myMap.put("3", "1");
myMap.put("4", "1");
myMap.put("5", "1");
myMap.put("6", "1");
System.out.println("ConcurrentHashMap before iterator: " + myMap);
Iterator<String> it = myMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
if (key.equals("3"))
myMap.put(key + "new", "new3");
}
System.out.println("ConcurrentHashMap after iterator: " + myMap);
// HashMap
myMap = new HashMap<String, String>();
myMap.put("1", "1");
myMap.put("2", "1");
myMap.put("3", "1");
myMap.put("4", "1");
myMap.put("5", "1");
myMap.put("6", "1");
System.out.println("HashMap before iterator: " + myMap);
Iterator<String> it1 = myMap.keySet().iterator();
while (it1.hasNext()) {
String key = it1.next();
if (key.equals("3"))
myMap.put(key + "new", "new3");
}
System.out.println("HashMap after iterator: " + myMap);
}
}
结果:
ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
ConcurrentHashMap after iterator: {3new=new3, 1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:922)
at java.util.HashMap$KeyIterator.next(HashMap.java:956)
at com.dxz.concurrent.hashmap.ConcurrentHashMapExample.main(ConcurrentHashMapExample.java:42)
查看输出,很明显ConcurrentHashMap可以支持向map中添加新元素,而HashMap则抛出了ConcurrentModificationException。
查看异常堆栈记录,可以发现是下面这条语句抛出异常:
String key = it1.next();
这就意味着新的元素在HashMap中已经插入了,但是在迭代器执行时出现错误。事实上,集合对象的迭代器提供快速失败(Fail-Fast)的机制,即修改集合对象结构或者元素数量都会使迭代器触发这个异常。
但是迭代器是怎么知道HashMap被修改了呢,我们可以一次取出HashMap的所有Key然后进行遍历。
HashMap包含一个修改计数器,当你调用它的next()方法来获取下一个元素时,迭代器将会用到这个计数器。
HashMap.java
/** * HashMap结构的修改次数 * 结构修改是指:改变了HashMap中mapping的个数或者其中的内部结构(比如,重新计算hash值) * 这个字段在通过Collection操作Hashmap时提供快速失败(Fail-fast)功能。 * (参见 ConcurrentModificationException)。 */ transient volatile int modCount;
现在为了证明上面的观点,我们对原来的代码做一点修改,使迭代器在插入新的元素后跳出循环。只要在调用put方法后增加一个break:
if(key.equals("3")){
myMap.put(key+"new", "new3");
break;
}
再执行修改后的代码,会得到下面的输出结果:
ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1}
HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}
HashMap after iterator: {3=1, 2=1, 1=1, 3new=new3, 6=1, 5=1, 4=1}
最后,如果我们不添加新的元素而是修改已经存在的键值对会不会抛出异常呢?
修改原来的程序并且自己验证一下:
//myMap.put(key+"new", "new3"); //新增key-value,出错 myMap.put(key, "new3");//修改value值,正确
it1.remove(); //删除key-value对,正确
ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
ConcurrentHashMap after iterator: {3new=new3, 1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}
HashMap after iterator: {3=new3, 2=1, 1=1, 6=1, 5=1, 4=1}
结果无报错。