uli
03/12/2021, 10:43 AMrunBlocking
, launched on the same single threaded dispatcher do not block each other. They share an event queue.
2. former runBlocking
will only return after later runBLocking
completes
(1) comes as a positive surprise
(2) is totaly unexpected and I’d consider it a bug
I’ll follow up in a thread with the demo codeimport kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.Dispatchers
val start by lazy { System.currentTimeMillis() }
fun log(TAG: String) {
val relTime = System.currentTimeMillis() - start
println("$TAG @${relTime}ms in ${Thread.currentThread()}")
}
fun main() {
runBlocking {
launch {
log("Start #1")
runBlocking {
log("Before delay #1")
delay(100)
log("After delay #1")
}
log("Done #1")
}
launch {
log("Start #2")
runBlocking {
log("Before delay #2")
delay(300)
log("After delay #2")
}
log("Done #2")
}
}
}
Start #1 @0ms in Thread[main @coroutine#2,5,main]
Start #2 @1ms in Thread[main @coroutine#3,5,main]
Before delay #1 @2ms in Thread[main @coroutine#4,5,main]
Before delay #2 @6ms in Thread[main @coroutine#5,5,main]
After delay #1 @105ms in Thread[main @coroutine#4,5,main]
After delay #2 @307ms in Thread[main @coroutine#5,5,main]
Done #2 @307ms in Thread[main @coroutine#3,5,main]
Done #1 @307ms in Thread[main @coroutine#2,5,main]
myanmarking
03/12/2021, 10:46 AMrunBlocking
will only return after both are completed -> seems not to be ituli
03/12/2021, 10:47 AMmyanmarking
03/12/2021, 10:47 AMuli
03/12/2021, 10:48 AMmyanmarking
03/12/2021, 10:52 AMlouiscad
03/12/2021, 1:47 PMuli
03/12/2021, 1:49 PMlouiscad
03/12/2021, 1:49 PMlaunch
, which is a child of the enclosing runBlocking
.uli
03/12/2021, 1:51 PMlouiscad
03/12/2021, 1:51 PMrunBlocking
behaves like coroutineScope { … }
uli
03/12/2021, 1:52 PMlouiscad
03/12/2021, 1:54 PM<http://Dispatchers.IO|Dispatchers.IO>
to the enclosing runBlocking { … }
. Doing blocking "concurrency" with a single thread will always not work as expected.uli
03/12/2021, 1:58 PMlouiscad
03/12/2021, 1:59 PMuli
03/12/2021, 1:59 PMlouiscad
03/12/2021, 2:00 PMuli
03/12/2021, 2:01 PMlouiscad
03/12/2021, 2:01 PMuli
03/12/2021, 2:02 PMlouiscad
03/12/2021, 2:03 PMuli
03/12/2021, 2:04 PMlouiscad
03/12/2021, 2:05 PMrunBlocking
calls happening on the blocked thread.uli
03/12/2021, 2:06 PMthen don't do it
louiscad
03/12/2021, 2:08 PMmyanmarking
03/12/2021, 2:11 PMuli
03/12/2021, 2:33 PMmyanmarking
03/12/2021, 2:35 PMuli
03/12/2021, 2:36 PMmyanmarking
03/12/2021, 2:40 PM