Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can something bad happen when using runBlocking from a coroutine?

From the documentation of runBlocking is it clear why it does not make sense to use it from a coroutine, e.g., nest it.

It even explicitly states:

This function should not be used from a coroutine.

However, it is possible to do so:

fun main(args: Array<String>) {
    runBlocking {
        runBlocking {
            println("hi")
        }
    }
}

The (IntelliJ) IDE complains a bit

OCvdVKx

but the code compiles and runs.

What can happen when done accidentally in a more complex setting? Crashes? Or maybe Deadlocks?

like image 685
Tobias Hermann Avatar asked Oct 15 '22 07:10

Tobias Hermann


1 Answers

What can happen when done accidentally in a more complex setting? Crashes? Or maybe Deadlocks?

No, nothing like that. In fact, runBlocking is specifically written to support nesting:

If the specified dispatcher is an event loop of another runBlocking, then this invocation uses the outer event loop.

The concern you mention is not actually related to nesting runBlocking calls, but a general concern of calling any blocking code from a coroutine. We use coroutines with the specific purpose of avoiding to block the thread, so it's usually an error to call blocking functions inside them. You'll get the same warning for Thread.sleep(), java.io calls etc.

like image 176
Marko Topolnik Avatar answered Oct 21 '22 02:10

Marko Topolnik