modCount是ArrayList中记录结构性修改次数的受保护字段,用于fail-fast机制;迭代器通过比对modCount与expectedModCount实现快速失败,单线程遍历时调用list.remove()也会触发ConcurrentModificationException。

Java ArrayList 的快速失败(fail-fast)机制,本质是通过 modCount 和迭代器内部维护的 expectedModCount 进行一致性校验——只要两者不相等,就抛出 ConcurrentModificationException。
modCount 是什么?
modCount 是 ArrayList(及其父类 AbstractList)中定义的一个受保护的整型字段,用于记录集合**结构性修改的次数**。所谓“结构性修改”,是指会改变集合大小或内部数组结构的操作,例如:
-
add()、remove()、clear() -
addAll()、removeAll()、retainAll() -
replaceAll()(JDK 8+)、sort()
注意:set() 不算结构性修改,它只替换元素,不改变 size 或底层数组长度,因此不会修改 modCount。
迭代器如何利用 modCount 实现 fail-fast?
当你调用 list.iterator() 时,会创建一个 Itr(内部私有迭代器类)。该迭代器在构造时,会把当前 ArrayList.modCount 的值拷贝到自己的 expectedModCount 字段中:
立即学习“Java免费学习笔记(深入)”;
Itr() {
expectedModCount = modCount;
}
此后每次调用 next() 或 remove() 前,都会检查是否一致:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
一旦发现不一致,立刻抛异常,阻止继续遍历——这就是“快速失败”:不保证线程安全,但能尽早暴露错误。
为什么单线程下也会触发?
很多人误以为 fail-fast 只在多线程并发修改时出现,其实**单线程中边遍历边修改也会触发**,因为 modCount 已被改写,而迭代器仍按旧值校验。例如:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
if ("b".equals(s)) {
list.remove(s); // ⚠️ 结构性修改 → modCount++
}
}
执行到第二次 next() 时,checkForComodification() 发现 modCount != expectedModCount,立即抛出异常。
如何安全地边遍历边删除?
必须使用迭代器自身的 remove() 方法,它会在删除后同步更新 expectedModCount:
-
iterator.remove():合法,会执行expectedModCount = modCount -
list.remove()或list.add():非法,会破坏一致性 - 也可用
removeIf()(JDK 8+),它是原子操作,内部已处理modCount同步
示例:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if ("b".equals(s)) {
it.remove(); // ✅ 安全
}
}
fail-fast 不是锁,也不提供并发保障,它只是一个调试辅助机制——靠 modCount 忠实记录变更、靠迭代器严格校验,让错误在发生时立刻显现。

















