仓颉 std.collection 中 ConcurrentModificationException 的触发场景与版本检测机制源码详解
仓颉 std.collection 中 ConcurrentModificationException 的触发场景与版本检测机制源码详解
本文聚焦仓颉标准库 std.collection 包中的 ConcurrentModificationException 异常类,完整梳理其两个构造函数的用法与示例、典型触发场景,并深入 concurrent_modification_exception.cj 及各容器迭代器源码,讲清楚"迭代期间检测到非同步修改"这一检测机制背后的 version/modCount 实现原理。读完后你将能够:在代码中正确构造、抛出与捕获该异常;准确判断哪些操作会触发它;并知道如何编写规避该异常的迭代与删除逻辑。
异常类定义与继承体系
std.collection 包提供的所有容器类均不支持并发(非同步)修改,当某些操作检测到这种修改时,会抛出 ConcurrentModificationException。该类声明如下:
public class ConcurrentModificationException <: Exception {
public init()
public init(message: String)
}
其父类型为 Exception,提供通用的异常消息、栈回溯与 toString 能力。
对照源码 concurrent_modification_exception.cj,可以看到该类还重写了父类的 getClassName 方法,使 toString 等输出能显示正确的类名:
public class ConcurrentModificationException <: Exception {
public init() {
super()
}
public init(message: String) {
super(message)
}
protected override func getClassName(): String {
return "ConcurrentModificationException"
}
}
从源码结构看,两个构造函数只是简单转发给父类;父类 Exception 在构造时会调用 fillInStackTrace 记录 PC 栈帧,供后续 printStackTrace 输出完整调用栈。因此捕获该异常后可以直接获取 message 属性与栈信息用于定位问题。
构造函数详解
init():无参构造
public init()
功能:构造一个不带异常消息的实例。
示例:
import std.collection.*
main(): Unit {
// Create a ConcurrentModificationException instance using the no-argument constructor
let exception = ConcurrentModificationException()
println("Created a no-argument ConcurrentModificationException instance")
// The exception can be thrown and caught
try {
throw ConcurrentModificationException()
} catch (e: ConcurrentModificationException) {
println("Caught a ConcurrentModificationException")
}
}
执行结果:
Created a no-argument ConcurrentModificationException instance
Caught a ConcurrentModificationException
init(message: String):带消息构造
public init(message: String)
功能:使用指定消息构造异常实例。
参数:
message: String —— 异常消息。
示例:
import std.collection.*
main(): Unit {
// Create a ConcurrentModificationException instance with a custom message
let message = "Concurrent modification exception: Container was modified during iteration"
let exception = ConcurrentModificationException(message)
println("Created a ConcurrentModificationException instance with message: ${exception.message}")
// Can throw and catch this exception
try {
throw ConcurrentModificationException("Container was modified during iteration")
} catch (e: ConcurrentModificationException) {
println("Caught exception: ${e.message}")
}
}
执行结果:
Created a ConcurrentModificationException instance with message: Concurrent modification exception: Container was modified during iteration
Caught exception: Container was modified during iteration
在自定义业务代码中,建议优先使用带消息的构造函数抛出该异常,消息内容应说明"哪个容器、在什么阶段被修改",便于排查。
典型触发场景
根据文档与源码印证,触发该异常的典型场景包括:
- 在 for-in 迭代期间修改容器:除 HashMapIterator 的 remove() 方法外,迭代过程中对容器增删元素都会触发异常。
- 使用 MapEntryView 等短生命周期视图时,底层容器内容发生变化:通过视图访问或更新数据时若检测到容器版本已变,同样抛出该异常。
此外,在 predicate 谓词回调内修改容器(如 removeIf、filter 场景)也会抛出该异常,下面结合源码逐一看清检测细节。
源码级检测机制:版本号比对
collection 包的并发修改检测并非真正的并发同步,而是一种版本(version)快照比对机制:迭代器或视图创建时记录容器的版本号,每次关键操作前重新读取版本号,一旦发现不一致即判定"内容被修改"并抛出 ConcurrentModificationException。
ArrayList 迭代器:myVersion 快照
在 array_list.cj 中,ArrayListIterator 构造时记录 initVersion = data.myVersion,随后每次 next() 都先做校验:
init(data: ArrayList<T>) {
myData = data
initVersion = data.myVersion
}
public func next(): Option<T> {
if (myData.myVersion != initVersion) {
throw ConcurrentModificationException()
}
// ...
}
而 ArrayList 的每次结构性修改(增删元素、removeIf 等)都会递增 myVersion 字段,从而让下一次 next() 立刻"抓现行"。
HashMap 迭代器:lockVersion 与 version()
HashMap 内部维护一个 modCount 版本计数,并暴露 version() 方法返回它(见 hash_map.cj):
@Frozen
func version(): Int64 {
return modCount
}
HashMapIterator 在初始化时锁定 lockVersion = map.version(),next() 与 remove() 每次调用前都比对(见 hash_map.cj):
public func next(): ?(K, V) {
if (lockVersion != data.version()) {
throw ConcurrentModificationException()
}
// ...
}
public func remove(): Option<(K, V)> {
if (lockVersion != data.version()) {
throw ConcurrentModificationException()
}
// ...
data.removePosition(item.hash, index)
isRemoved = true
lockVersion = data.version() // 删除后刷新版本快照
return Some((item.key, item.value))
}
注意 remove() 是迭代中唯一"安全删除"的出口:它先校验版本,删除后主动执行 lockVersion = data.version() 刷新快照,因此迭代中连续调用 next()/remove() 不会误报异常;但如果绕过迭代器直接对 HashMap 增删,next() 的下一轮校验就会抛出 ConcurrentModificationException。这与官方文档中"except for the remove() method of HashMapIterator"的例外说明完全对应。
HashMapEntryView:视图操作的版本校验
HashMapEntryView(MapEntryView 的 HashMap 实现)对 getKey()、getValue()、setValue() 三个方法都做了同样的版本检查(见 hash_map.cj):
func getKey(): K {
if (lockVersion != map.version()) {
throw ConcurrentModificationException()
}
return _key
}
setValue() 在插入分支中还会执行 map.modCount++ 与 lockVersion = map.modCount,即合法的视图写入会同步推进版本快照。这也解释了文档中"当使用短生命周期类型如 MapEntryView 时,若底层容器内容被修改,将抛出该异常"的行为——任何使 map.version() 前移的外部修改,都会让视图在下一次操作时失守。
predicate 回调中的修改:带自定义消息的抛出
LinkedList 的 removeIf 会在谓词执行前后比对 _version,若谓词内部对列表做了增删,则抛出带明确说明的异常(见 linked_list.cj):
public func removeIf(predicate: (T) -> Bool): Unit {
var node = _head
while (let Some(n) <- node) {
node = n.next
let lockVersion = _version
let needDelete = predicate(n.value)
if (_version != lockVersion) {
throw ConcurrentModificationException("The predicate cannot contain a modify operation.")
}
// ...
}
}
同样的检查模式也出现在 hash_map.cj、array_list.cj、tree_map.cj、array_deque.cj 等容器的谓词类操作中,抛出时均携带 "The predicate cannot contain a modify operation." 消息。因此在标准库文档中,HashMap/HashSet/TreeMap/TreeSet/LinkedList 等的 removeIf 类 API 的 @throws 说明均指向本异常(参见 collection_package_class.md 中的相关条目)。
使用建议
结合上述源码证据,可以归纳出规避 ConcurrentModificationException 的实践要点:
- 不要直接在 for-in 循环体内对容器增删。
ArrayListIterator.next()、HashMapIterator.next()等在版本不一致时会立即抛出该异常,这是刻意的快速失败设计。 - 需要边迭代边删除时,使用迭代器自带的
remove()。以HashMapIterator.remove()为例,它会在删除后刷新lockVersion,是当前文档明确允许的迭代期修改出口。 predicate回调必须保持"纯"。removeIf等 API 会在谓词执行后比对版本,回调内部修改容器会触发"The predicate cannot contain a modify operation."。- 使用
MapEntryView等视图时,将其生命周期控制在"容器不被外部修改"的窗口内,并在视图操作前后避免对容器做结构性改动;视图方法在检测到lockVersion != map.version()时会抛出本异常。 - 捕获后利用
message定位。容器自身抛出的异常大多不带消息(init()构造),而谓词类操作带固定说明文本;业务代码自行抛出时建议使用init(message: String)提供上下文。
小结
ConcurrentModificationException 是 std.collection 包对"迭代/视图期间非同步修改"这一危险操作的统一防护信号。从 concurrent_modification_exception.cj 的实现看,它本身只是一个轻量的 Exception 子类(两个构造函数加 getClassName);真正的工作由各容器迭代器与视图中的版本号快照比对完成——array_list.cj 的 myVersion 检查、hash_map.cj 中 lockVersion 与 version() 的比对、以及 LinkedList.removeIf 对谓词副作用的拦截,共同构成了 collection 包的并发修改检测体系。理解这套机制后,配合迭代器 remove() 的正确用法,即可在保持集合线程安全语义的同时,写出不会误触该异常的迭代逻辑。