runBlocking is called in a coroutine and blocks the thread it runs on

tx0/kotlin:run-blocking-in-coroutinedefaultwarningreliability/concurrencydepth fastbug, concurrency

What it finds

runBlocking in a suspend function, or in a lambda that a coroutine builder runs, blocks the thread of the coroutine until the inner work is done. On a dispatcher with few threads this starves other coroutines and can deadlock when the inner work needs the same thread. The coroutines documentation says not to use it from a coroutine.

The code counts as running in a coroutine in the body of a suspend function, and in a lambda passed to a builder such as launch, async, withContext or runBlocking itself, also through lambdas that run in place, such as those of let or forEach. Files that do not import from kotlinx.coroutines are left alone.

From the rule's source, blocking_in_coroutine.rs.

Example from the rule's tests
import kotlinx.coroutines.* suspend fun load(): Int {    val cached = runBlocking { fetch() }tx0 reports: runBlocking inside a coroutine    listOf(1).forEach {        runBlocking { fetch() }tx0 reports: runBlocking inside a coroutine    }    return cached} fun main() {    runBlocking {        launch {            runBlocking { fetch() }tx0 reports: runBlocking inside a coroutine        }    }    thread {        runBlocking { fetch() }    }} fun plain() = runBlocking { fetch() }
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

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:

tx0.toml
[rules]
"tx0/kotlin:run-blocking-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:run-blocking-in-coroutine] reason="..."

tx0 explain tx0/kotlin:run-blocking-in-coroutine shows the same in the terminal. Found a false positive? Report it.