关注我,精彩文章第一时间推送给你
12-e7c4a452-0
- 首先我尝试写了一下这段代码如下:
private static void testForeachAddOrRemove() {
var list = new ArrayList<String>();
list.add("1");
list.add("2");
for (var s : list) {
if ("2".equals(s)) {
list.remove(s);
}
}
list.forEach(System.out::println);
}
调用结果:异常ConcurrentModificationException如下:
12-e7c4a452-1- 如图所示提示ArrayList.java 1043行抛出异常,我用的JDK11,马上点进去看了源码,正是如下这行抛出的异常,原因是modCount != expectedModCount那么这两个变量什么意思呢?继续读源码
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
- modCount是在抽象类AbstractList中被定义,是集合结构修改的次数,例如添加元素、删除元素等结构调整都会使modCount++,下面列举add()和删除的源码,其他结构化修改也会modCount++,这里不做列举。
public boolean remove(Object o) {
final Object[] es = elementData;
final int size = this.size;
int i = 0;
found: {
if (o == null) {
for (; i < size; i++)
if (es[i] == null)
break found;
} else {
for (; i < size; i++)
if (o.equals(es[i]))
break found;
}
return false;
}
fastRemove(es, i);//-----------重点重点重点------------------
return true;
}
private void fastRemove(Object[] es, int i) {
modCount++;//---------------重点重点重点------------------
final int newSize;
if ((newSize = size - 1) > i)
System.arraycopy(es, i + 1, es, i, newSize - i);
es[size = newSize] = null;
}
public boolean add(E e) {
modCount++;//-------重点重点重点----------
add(e, elementData, size);
return true;
}
- expectedModCount是在ArrayList的内部类Itr中声明的,Itr实现类迭代器接口,这里做了下精简只保留了变量声明和next()方法、remove()方法,可以看到迭代器的实现里声明了expectedModCount = modCount;这里理解成预期结构化调整次数 = 结构化调整次数,为什么每次迭代next()和remove()之前都要检查是否相等呢?可以理解成如果没有这个校验,某个线程删除了list的一个元素,此时next方法不知道size变更了,依然去取数组里的数据,会导致数据为null或ArrayIndexOutOfBoundsException异常等问题。
/**
* An optimized version of AbstractList.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;//-------------重点重点重点---------------
@SuppressWarnings("unchecked")
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();//-----------重点重点重点---------------------
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;//------------重点重点重点-------------------
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)//-----------重点重点重点---------------------
throw new ConcurrentModificationException();
}
}
- 这里串起来就好理解了,由于增强for循环底层反编译之后是迭代器实现的,所以在iterator初始化的时候(也就是for循环开始处),expectedModCount = modCount之后for循环内部进行remove实际上用的是ArrayList的remove()方法,执行了modCount++,而进行for循环底层进行next()迭代的时候进行了checkForComodification()方法判断,modCount++了next()并不知道,所以造成不相等抛出异常。
- 那为什么使用迭代器可以进行删除而不抛出异常呢?因为看上面的源码,迭代器内部的remove()方法的实现在调用ArrayList.this.remove()进行删除之后,expectedModCount = modCount;及时同步了这两个变量的值。所以使用迭代器删除不会造成问题,写法如下:
private static void testForeachAddOrRemove() {
var list = new ArrayList<String>();
list.add("1");
list.add("2");
/*for (var s : list) {
if ("2".equals(s)) {
list.remove(s);
}
}*/
var iterator = list.iterator();
while (iterator.hasNext()) {
var str = iterator.next();
if ("2".equals(str)) {
iterator.remove();
}
}
list.forEach(System.out::println);
}
建议:如果是JDK8或者以上版本,推荐使用removeIf进行删除,这也是IDEA推荐写法
写法如下:
private static void testForeachAddOrRemove() {
var list = new ArrayList<String>();
list.add("1");
list.add("2");
/*for (var s : list) {
if ("2".equals(s)) {
list.remove(s);
}
}*/
/*var iterator = list.iterator();
while (iterator.hasNext()) {
var str = iterator.next();
if ("2".equals(str)) {
iterator.remove();
}
}*/
list.removeIf("2"::equals);
list.forEach(System.out::println);
}
- 同样可以阅读一下removeIf()的源码
@Override
public boolean removeIf(Predicate<? super E> filter) {
return removeIf(filter, 0, size);
}
/**
* Removes all elements satisfying the given predicate, from index
* i (inclusive) to index end (exclusive).
*/
boolean removeIf(Predicate<? super E> filter, int i, final int end) {
Objects.requireNonNull(filter);
int expectedModCount = modCount;//-----------重点重点重点--------------
final Object[] es = elementData;
// Optimize for initial run of survivors
for (; i < end && !filter.test(elementAt(es, i)); i++)
;
// Tolerate predicates that reentrantly access the collection for
// read (but writers still get CME), so traverse once to find
// elements to delete, a second pass to physically expunge.
if (i < end) {
final int beg = i;
final long[] deathRow = nBits(end - beg);
deathRow[0] = 1L; // set bit 0
for (i = beg + 1; i < end; i++)
if (filter.test(elementAt(es, i)))
setBit(deathRow, i - beg);
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
modCount++;//-------------重点重点重点------------
int w = beg;
for (i = beg; i < end; i++)
if (isClear(deathRow, i - beg))
es[w++] = es[i];
shiftTailOverGap(es, w, end);
return true;
} else {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
return false;
}
}
网友评论