Thread.sleep blocks the thread of a coroutine instead of suspending it
What it finds
Thread.sleep(100) or TimeUnit.SECONDS.sleep(1) in a coroutine blocks the thread the coroutine runs on, so no other coroutine can use it meanwhile, and the coroutine cannot be cancelled while it sleeps. delay suspends instead.
The code counts as running in a coroutine as for run-blocking-in-coroutine, except in the lambda of runBlocking, whose thread waits anyway.
From the rule's source, sleep_in_coroutine.rs.
import kotlinx.coroutines.*import java.util.concurrent.TimeUnit suspend fun poll() { Thread.sleep(100)tx0 reports: Thread.sleep blocks the thread of the coroutine TimeUnit.SECONDS.sleep(1)tx0 reports: TimeUnit.SECONDS.sleep blocks delay(100)} fun worker(scope: CoroutineScope) { scope.launch(Dispatchers.Default) { Thread.sleep(10)tx0 reports: Thread.sleep blocks } runBlocking { Thread.sleep(10) } Thread.sleep(10)} Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/kotlin:sleep-in-coroutine" = "off"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/kotlin:sleep-in-coroutine] reason="..."tx0 explain tx0/kotlin:sleep-in-coroutine shows the same in the terminal. Found a false positive? Report it.