java iterator 的 fail-fast 机制是一种快速失败的安全策略,当检测到集合在迭代过程中被结构性修改时,立即抛出 concurrentmodificationexception。具体做法是在创建迭代器时记录集合的 modcount,每次调用 next() 或 remove() 时检查当前 modcount 是否发生变化,若不一致则说明发生了并发修改。需要注意的是,该机制并非线程安全保证,仅用于检测单线程下的逻辑错误;对于多线程环境应使用 copyonwritearraylist 等并发容器。

next() 方法如何触发 ConcurrentModificationException
通过对比正常遍历与中途修改集合的行为,可以清晰看到异常触发的时机。在单线程环境下,如果在 foreach 循环中直接调用集合的 add 或 remove 方法,迭代器会在下一次获取元素时发现版本号不匹配并报错。
import java.util.*;
public class FailFastDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
// 正常遍历
for (String s : list) {
System.out.println(s);
}
// 尝试在迭代中修改
try {
for (String s : list) {
if (s.equals("A")) {
list.add("C"); // 触发 fail-fast
}
}
} catch (ConcurrentModificationException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
}
}预期结果:先打印 A 和 B,随后捕获 ConcurrentModificationException。这验证了迭代器在发现结构变化时的即时反应。

立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
modCount 字段在不同集合实现中的行为差异
虽然 ArrayList 是典型的 fail-fast 实现,但不同集合类对 modCount 的管理方式略有不同。例如 LinkedList 同样维护 modCount,而 HashMap 的迭代器也遵循相同规则。关键在于理解哪些操作会改变 modCount。
import java.util.*;
public class ModCountCheck {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("x", 1);
map.put("y", 2);
Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entry = it.next();
if (entry.getKey().equals("x")) {
map.remove("y"); // 修改结构
}
}
}
}预期结果:程序运行时会抛出 ConcurrentModificationException。这表明 HashMap 的 EntrySet 迭代器同样受 modCount 保护。相比之下,如果使用 iterator.remove() 则是安全的,因为它会同步更新 modCount。

使用 Iterator.remove() 避免 ConcurrentModificationException
在迭代过程中需要移除元素时,必须使用迭代器提供的 remove() 方法,而不是直接调用集合的 remove()。这是因为 iterator.remove() 会正确更新 modCount,从而保持版本一致性。
import java.util.*;
public class SafeRemove {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("B")) {
it.remove(); // 安全移除
}
}
System.out.println(list); // [A, C]
}
}预期结果:输出 [A, C],无异常抛出。这证明了正确使用迭代器方法可以避免 fail-fast 机制的误报。在实际开发中,应优先使用这种方式进行条件过滤,而非依赖外部集合操作。

















