Iterator遍历中修改集合会抛ConcurrentModificationException,因fail-fast机制通过modCount与expectedModCount比对检测并发修改;仅iterator.remove()安全,且需先调用next();多线程下即使只读也可能触发异常;应选用CopyOnWriteArrayList或ConcurrentHashMap等并发容器。
ConcurrentModificationException
不安全。Java 的 Iterator 默认是“快速失败”(fail-fast)机制,只要在遍历时通过集合本身(如 list.add()、set.remove())修改结构,下一次调用 iterator.next() 或 iterator.hasNext() 就会立即抛出 ConcurrentModificationException。
这是设计使然,不是 bug —— 它靠维护一个 modCount(修改计数器)和 expectedModCount(迭代器预期值)比对来检测并发修改。
iterator.remove() 是安全的,它会同步更新 expectedModCount
forEachRemaining() 同样受保护,内部也走的是迭代器自己的删除逻辑iterator.remove()
不能用 for-each 循环配合 collection.remove(),也不能在普通 for 中正向遍历时
(int i = 0; ...)remove(i)(会跳过下一个元素)。
Listlist = new ArrayList<>(Arrays.asList("a", "b", "c", "b")); Iterator it = list.iterator(); while (it.hasNext()) { String s = it.next(); if ("b".equals(s)) { it.remove(); // ✅ 唯一安全的删除方式 } } // 结果:["a", "c"]
it.remove() 前必须已调用过 it.next(),否则抛 IllegalStateException
next() 最多对应一次 remove(),重复调用会报错removeIf() 更简洁(但底层仍是基于迭代器)CopyOnWriteArrayList 和 ConcurrentHashMap 是为并发遍历设计的标准 ArrayList、HashMap 的迭代器都不支持遍历时并发修改;若业务确实需要「读多写少 + 遍历中可能被改」,应换并发容器:
CopyOnWriteArrayList:遍历时操作的是快照,增删不影响当前迭代器,但写操作开销大、不适用于高频修改场景ConcurrentHashMap:其 keySet().iterator() 不抛 CME,但不保证反映最新全部修改(弱一致性),适合统计类遍历Vector 或 Hashtable 的迭代器仍是 fail-fast 的,**不是**线程安全替代方案Iterator,风险完全一致for (String s : list) 编译后等价于显式获取 iterator() 并调用 hasNext()/next(),所以:
Listlist = new ArrayList<>(Arrays.asList("x", "y")); for (String s : list) { if ("x".equals(s)) { list.remove(s); // ❌ 这里没报错,但下一轮 next() 时抛 ConcurrentModificationException } }
next() 或 hasNext(),不是你写的 remove() 那行foreach 标签、Spring 的 @EventListener 批量处理)会隐式触发迭代,而你在回调里又去改原集合 —— 这种链路里的 CME 很难一眼定位。