I'm confused about the behavior of this code. ``` ...
# coroutines
c
I'm confused about the behavior of this code.
Copy code
@Test
    fun test() {
        val start = TimeSource.Monotonic.markNow()

        runBlocking {
            launch {
                runBlocking {
                    delay(1.seconds)
                    println("world! (at ${start.elapsedNow()}, in ${Thread.currentThread().name})")
                }
            }

            delay(1.milliseconds)
            println("Hello (at ${start.elapsedNow()}, in ${Thread.currentThread().name})")
        }
    }
I expected that: • The first
launch
registers, execution continues •
delay(1ms)
forces the
launch
to execute before the
println
• The
launch
executes
runBlocking
. This takes over the current thread. Since the entire test is running in another
runBlocking
, the outer
runBlocking
has no thread to execute on, and so the
println("Hello …")
cannot execute. • The inner
runBlocking
executes completely. • The outer
runBlocking
finishes. And so I expected the output to be:
Copy code
World! (at ~1s, in worker)
Hello (at ~1.0001s, in worker)
However, when I run it, I get:
Copy code
Hello (at 17.471514ms, in Test worker @coroutine#1)
world! (at 1.020449895s, in Test worker @coroutine#3)
Does the inner
runBlocking
share its event queue with the outer
runBlocking
somehow? Why is the outer
runBlocking
able to execute even though its thread is blocked on in the inner one?
s
The dispatcher used by the runBlocking call is one that has a pool of multiple threads?
d
Does the inner
runBlocking
share its event queue with the outer
runBlocking
somehow
Yes: https://github.com/Kotlin/kotlinx.coroutines/issues/3982, https://github.com/Kotlin/kotlinx.coroutines/issues/4215
c
Uh
I actually preferred when
runBlocking
dead-locked in this situation. It's bad code anyway, as the job relationship isn't propagated. Making it fail catastrophically was a good way to force users not to write it.