llms.txt: machine-readable documentation index. Markdown version of this page is also available.

Kotlin 语言参考文档 中文版 Help

测试任意代码

Lincheck 提供了 runConcurrentTest() 函数, 用于测试任意并发代码.

runConcurrentTest() 函数会多次执行一段并发代码, 并通过模型检查, 探索它可能的执行调度.

使用 Lincheck 测试并发代码, 请遵循下面的步骤:

  1. 创建测试类:

    class NewConcurrentTest { // 测试 }
  2. 使用 runConcurrentTest(), 创建一个测试函数, 作为成员函数.

    @Test fun test() = runConcurrentTest(100_000) { // 并发代码 }
  1. 运行测试. 如果测试失败, Lincheck 会生成一份报告, 其中包含导致错误行为的执行调度.

| ------------------------------------------------------------------------------- | | Main Thread | Thread 1 | Thread 2 | | ------------------------------------------------------------------------------- | | thread(block = Lambda#2): Thread#1 | | | | thread(block = Lambda#3): Thread#2 | | | | switch (reason: waiting for Thread 1 to finish) | | | | | | run() | | | | counter ➜ 0 | | | | switch | | | run() | | | | counter ➜ 0 | | | | counter = 1 | | | | | counter = 1 | | Thread#1.join() | | | | Thread#2.join() | | | | counter.element ➜ 1 | | | | assertEquals(2, 1): threw AssertionFailedError | | | | ------------------------------------------------------------------------------- |

示例: 测试 ConcurrentHashMap 函数

请看以下针对 ConcurrentHashMap 函数的测试:

import org.jetbrains.lincheck.* import java.util.concurrent.* import kotlin.concurrent.* import kotlin.test.* // 这个测试演示一种死锁情况, 由 2 个线程, 以相反的顺序嵌套调用 `computeIfAbsent` 而导致. class ConcurrentHashMapDeadlock { @Test fun test() = Lincheck.runConcurrentTest { val map = ConcurrentHashMap<String, String>() // 对 `key1` 加锁, 更新 `key2`. val thread1 = thread { map.computeIfAbsent("key1") { map.computeIfAbsent("key2") { "value2" } "value1" } } // 对 `key2` 加锁, 更新 `key1`. val thread2 = thread { map.computeIfAbsent("key2") { map.computeIfAbsent("key1") { "value1" } "value2" } } // 等待 2 个线程完成. thread1.join() thread2.join() } }

测试会失败, 因为 Lincheck 找到了导致死锁的执行调度:

  1. 线程 2 将 key2 映射到索引为 1 的存储桶, 对这个存储桶加锁, 然后开始执行 computeIfAbsent("key1"). 在线程 2 映射 key1 并对 key1 的存储桶加锁 之前, 执行从线程 2 切换到线程 1.

  2. 线程 1 将 key1 映射到索引为 0 的存储桶, 对这个存储桶加锁, 然后开始执行 computeIfAbsent("key2"). 线程 1 将 key2 映射到索引为 1 的存储桶, 并尝试对它加锁, 但这个存储桶已被线程 2 锁定. 执行从线程 1 切换到线程 2.

  3. 线程 2 尝试对包含 key1 的存储桶加锁, 但这个存储桶已被线程 1 锁定.

两个线程都无法继续执行, 因此发生死锁.

Lincheck 对失败的测试的报告截图

下一步

学习如何 使用 Lincheck 测试数据结构.

2026/11/28