Skip to content

Commit 1bbc60e

Browse files
committed
Clarify that using runBlocking in suspend functions is allowed
A user raised a concern that the internal coroutines machinery may break if `runBlocking` is used somewhere deeply in the call stack. Calling `runBlocking` from a `suspend` functions can lead to deadlocks naturally due to blocking the thread, or to surprising event ordering, but nothing is expected to break. This commit clarifies the exact danger of calling `runBlocking` from `suspend` functions.
1 parent 761bdeb commit 1bbc60e

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

kotlinx-coroutines-core/jvm/src/Builders.kt

+16-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,22 @@ import kotlin.coroutines.*
1010

1111
/**
1212
* Runs a new coroutine and **blocks** the current thread _interruptibly_ until its completion.
13-
* This function should not be used from a coroutine. It is designed to bridge regular blocking code
14-
* to libraries that are written in suspending style, to be used in `main` functions and in tests.
13+
*
14+
* It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in
15+
* `main` functions and in tests.
16+
*
17+
* Calling [runBlocking] from a suspend function is redundant.
18+
* For example, the following code is incorrect:
19+
* ```
20+
* suspend fun loadConfiguration() {
21+
* // DO NOT DO THIS:
22+
* val data = runBlocking { // <- redundant and blocks the thread, do not do that
23+
* fetchConfigurationData() // suspending function
24+
* }
25+
* ```
26+
*
27+
* Here, instead of releasing the thread on which `loadConfiguration` runs if `fetchConfigurationData` suspends, it will
28+
* block, potentially leading to thread starvation issues.
1529
*
1630
* The default [CoroutineDispatcher] for this builder is an internal implementation of event loop that processes continuations
1731
* in this blocked thread until the completion of this coroutine.

0 commit comments

Comments
 (0)