//并发修改异常:运行以下下代码会抛出该异常--ConcurrentModificationException
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("java");
Iterator<String> it = list.iterator();
while(it.hasNext()){
String s = it.next();
if (s.equals("hello")){
list.add("javaee");
}
System.out.println(s);
}
/*运行结果:
hello
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:911)
at java.util.ArrayList$Itr.next(ArrayList.java:861)
at it.heima.date0803.Demo.main(Demo.java:95)
异常指向next方法,该方法是迭代器it调用,迭代器是接口,由List对象调用iterator方法返回,List的对象是ArrayList
向上转型,找到ArrayList, 查看重写的iterator方法,并且我们使用list对象调用add方法,一并找到ArayList中的add
方法,继续跟进iterator()中返回的Itr,发现他是内部类,无参构造权限修饰符为默认,Itr() {},属性分别为
0,-1,0,然后调用next方法,方法中先调用checkForComodification();这个方法中做判断
if(modCount != expectedModCount),就会抛出并发修改异常ConcurrentModificationException();
在list.add时候,ArrayList对象调用了add方法,首先走这个ensureCapacityInternal(size + 1),
这里面 modCount++;所以Itr判断时候modCount != expectedModCount,抛出异常*/
public class ArrayList<E> extends AbstractList<E>implements List<E>{
public Iterator<E> iterator() {
return new Itr();
}
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
}
// Itr类:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
并发修改异常源码分析
最新推荐文章于 2024-04-19 18:53:13 发布