java集合可分为线程安全和线程不安全两种,本篇主要讲述线程不安全的集合,如ArrayList,HashMap等集合内部的一个特性,fast-fail,也是对之前文章HashMap的源码解读的一个补充。
以ArrayList为例,我们都知道在使用增强for循环或foreach中无法进行remove或add操作,不然会报ConcurrentModificationException,如下代码
public class Test {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
for (Object object : list) {
list.remove(object);
}
}
}
阿里巴巴代码规范中也有提到这点
那到底是为什么会出现这种情况呢?原因就在于这篇文章要讲的知识点,fast-fail快速失败。
首先我们要知道一点,什么情况下会引发ConcurrentModificationException。
我们点开ArrayList源码查看一下,我们知道foreach和增强for循环底层用的都是迭代器的方法,也就是next(),那我们直接去查看这个方法的代码
@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];
}
我们会发现中间调用了一个方法,checkForComodification(),这个方法是重点,我们接着点进去看
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
他对modcount和expectedModCount进行了比较,如果不相等则抛出异常,那这个modCount是什么呢,他在什么时候会变化呢,我们可以全局搜索一下modCount,可以发现在remove,clear这些方法中都会有modCount++这段代码,也就是每执行一次remove,modCount就会加一,然而我们并没有看到expectedModCount的修改,所以两者必然不会相等,这也就是为什么在增强for循环中一边遍历一边删除会报错。
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 remove method that skips bounds checking and does not
* return the value removed.
*/
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; // clear to let GC do its work
}
那使用迭代器的移除就不会有这个问题了吗?我们还是看一下源码
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();
}
}
可以看到迭代器的remove在执行时也会进行一次判断,此时并未移除对象,所以ModCount还未进行变化,当移除完后会将ModCount再赋值给expectedModCount,会进行一次同步,此时两者还是相等,所以并不会报错。
注:当我们使用get方法根据下标获取对象时并不会有这个问题,最多是因为移除导致集合长度变化从而获取值出问题。