fail-fast 是 Java 集合的快速失败机制,通过 modCount 与 expectedModCount 校验检测遍历中结构修改,触发 ConcurrentModificationException;它非线程安全保证,仅用于单线程逻辑错误调试,且仅对集合自身方法修改有效。
ConcurrentModificationException
Java 集合(如 ArrayList、HashMap、HashSet)的迭代器默认启用 fail-fast 机制:一旦检测到集合在迭代过程中被结构上修改(增/删元素),就立即抛出 ConcurrentModificationException。这不是线程安全保证,而是一种**快速失败的调试辅助机制**。
核心原理是维护一个 modCount(修改计数器)和迭代器持有的 expectedModCount。每次调用 add()、remove() 等结构变更方法,modCount 自增;每次迭代器调用 next() 或 hasNext() 前,都会校验二者是否一致。
for-each 遍历边调用 list.remove(obj)
CopyOnWriteArrayList、ConcurrentHashMap 是 fail-safe,不抛此异常最典型的错误写法是用增强 for 循环删除元素:
for (String s : list) {
if (s.equals("bad")) {
list.remove(s); // ❌ 触发 ConcurrentModificationException
}
}
正确做法取决于需求:
Iterator.remove()(唯一安全的遍历中删除方式):Iteratorit = list.iterator(); while (it.hasNext()) { String s = it.next(); if (s.equals("bad")) { it.remove(); // ✅ 安全,同步更新 expectedModCount } }
removeIf():list.removeIf(s -> s.equals("bad")); // ✅ 内部使用迭代器 removestream().filter().collect(),避免原集合修改modCount 不是线程安全变量,别依赖它做同步modCount 是普通 int 字段,未加 volatile 或同步保护。它的作用仅限于**同一
线程内检测逻辑错误**,不能用于多线程协调或状态判断。
modCount 可能因指令重排或缓存不一致导致校验失效(即漏报)ArrayList 的 add() 本身非原子,多线程写仍可能数据丢失或数组越界CopyOnWriteArrayList(适合读多写少)、ConcurrentHashMap(高并发键值场景)若继承 AbstractList 等抽象类,modCount 已由父类维护,只需在所有结构修改方法中调用 super.modCount++(通常已由父类方法完成)。关键是在自定义 Iterator 中同步 expectedModCount:
private class MyIterator implements Iterator{ private int expectedModCount = modCount; // 初始化时捕获 private int cursor = 0; public E next() { if (modCount != expectedModCount) { // 每次 next 前校验 throw new ConcurrentModificationException(); } // ... 实际逻辑 } public void remove() { // ... 删除逻辑 expectedModCount = modCount; // 同步更新 } }
注意:如果集合允许外部绕过 API 直接修改底层结构(如暴露数组引用),fail-fast 就会失效——这属于设计缺陷,应避免。
真正容易被忽略的是:fail-fast 仅对「集合自身方法触发的修改」有效。反射改 modCount、直接操作底层数组、或子类未正确维护计数,都会让这个机制形同虚设。