调试探针:DebugProbes
源:kotlinx-coroutines-debug 官方指南
在异步世界中,堆栈跟踪 (Stack Trace) 往往是碎片化的。DebugProbes 提供了上帝视角的协程快照。
安装与性能警示
DebugProbes 通过 Java Agent 或 Bytecode Instrument 注入钩子。
- 性能开销: 显著增加内存使用和 CPU 指令。
- 使用场景: 仅限 DEBUG 构建 或 自动化测试。千万不要带上线!
kotlin
// Android Application.onCreate
if (BuildConfig.DEBUG) {
DebugProbes.install()
}核心功能
1. 打印所有活跃协程 (dumpCoroutines)
这比线程 Dump 强大得多,因为它包含挂起状态的协程。
kotlin
DebugProbes.dumpCoroutines()输出解读:
text
Coroutine "coroutine#1":StandaloneCoroutine{Active}@...
at kotlinx.coroutines.DelayKt.delay(Delay.kt:125) // 停在这里
at com.example.MyViewModel.loadData(MyViewModel.kt:34) // 你的业务代码
at com.example.MyActivity.access$loadData(...)2. Job 树状图 (printJobLayout)
排查 Job 泄漏 的有效工具。能清晰看到谁是谁的父协程。
kotlin
DebugProbes.printJobLayout()测试继承:死锁与泄漏检测
在单元测试中,结合 DebugProbes 可以自动检测测试结束时是否还有遗留的协程。
kotlin
@Test
fun testLeak() {
DebugProbes.withDebugProbes {
// 运行你的业务逻辑
// ...
// 如果这里有协程没跑完,DebugProbes 会在控制台报警并打印堆栈
}
}IDEA 调试器集成
现在的 IntelliJ IDEA / Android Studio 已经内置了 Coroutines Tab。
- 当断点命中时,在 Debug 窗口中切换到
Coroutines标签页,可以直接看到可视化的协程列表。 - 这本质上也是利用了
DebugProbes的元数据,但体验更 GUI 化。