进度保证
很多并发算法会提供 非阻塞的进度保证, 例如无等待(Wait-Freedom), 无锁(Lock-Freedom), 或无阻塞(Obstruction-Freedom).
Lincheck 只支持验证无阻塞(Obstruction-Freedom). 但是, 由于无锁(Lock-Freedom)和无等待(Wait-Freedom)算法也具有无阻塞性, 因此违反无阻塞性也意味着违反这些更强的保证.
请使用 checkObstructionFreedom 选项, 验证程序的无阻塞性保证:
Lincheck 会检查当其他所有线程暂停时, 某个线程是否仍能取得进展, 从而验证无阻塞性. 如果线程的执行 陷入循环, Lincheck 会报告检测到活跃锁(Active Lock).
如果某些函数有意设计为阻塞操作, 可以使用 @Operation(blocking = true) 标记这类函数, 以避免出现误报.
示例: 测试 ConcurrentHashMap 的无阻塞性
在这个示例中, 你将测试 ConcurrentHashMap 数据结构的 put() 函数.
创建
ConcurrentHashMapTest.kt文件.为
ConcurrentHashMap数据结构创建测试类, 并声明put()函数:class ConcurrentHashMapTest { private val map = ConcurrentHashMap<Int, Int>() @Operation fun put(key: Int, value: Int) = map.put(key, value) }声明测试函数, 并启用
checkObstructionFreedom()选项:@Test fun modelCheckingTest() = ModelCheckingOptions() .checkObstructionFreedom() .threads(2) .actorsPerThread(1) .check(this::class)threads和actorsPerThread选项用来减少可能的执行场景数量. 这些选项不会改变测试的通过或失败状态, 但能够显著的缩短测试时间.运行测试. 测试应该会失败, 并显示以下报告:
= The algorithm should be non-blocking, but an active lock is detected = | --------------------- | | Thread 1 | Thread 2 | | --------------------- | | put(1, 0) | put(1, 1) | | --------------------- | The following interleaving leads to the error: | -------------------------------------------------------------------------------------------------------------- | | Thread 1 | Thread 2 | | -------------------------------------------------------------------------------------------------------------- | | put(1, 0): <hung> | | | map.put(1, 0) | | | putVal(1, 0, false) | | | spread(1): 1 | | | table ➜ null | | | loop(1 iterations) at ConcurrentHashMap.putVal(ConcurrentHashMap.java:1016) | | | <iteration 1> | | | initTable() | | | loop(1 iterations) at ConcurrentHashMap.initTable(ConcurrentHashMap.java:2293) | | | table ➜ null | | | switch | | | | put(1, 1): <hung> | | -------------------------------------------------------------------------------------------------------------- |为
put()函数的注解添加blocking = true选项:@Operation(blocking = true) fun put(key: Int, value: Int) = map.put(key, value)重新运行测试. 测试应该成功通过.
示例: 测试 ConcurrentSkipListMap 的无阻塞性
在这个示例中, 你将测试非阻塞数据结构 ConcurrentSkipListMap 的 put() 函数.
创建
ConcurrentSkipListMapTest.kt文件.为
ConcurrentSkipListMap数据结构创建测试类, 并声明put()函数:class ConcurrentSkipListMapTest { private val map = ConcurrentSkipListMap<Int, Int>() @Operation fun put(key: Int, value: Int) = map.put(key, value) }声明测试函数, 并启用
checkObstructionFreedom()选项:@Test fun modelCheckingTest() = ModelCheckingOptions() .checkObstructionFreedom() .check(this::class)运行测试. 测试应该成功通过.