David Kubecka
10/16/2023, 1:52 PMrunBlocking
?
Directly via runBlocking parameter
runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
...
}
or via withContext
?
runBlocking {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
...
}
}
Quick debugging confirms my interpretation of the documentation that in the second case the internal eventLoop
is not defined although I have no clue exactly what consequences this has. Can anyone shed more light on this?simon.vergauwen
10/16/2023, 2:11 PMrunBlocking
has a context
parameter, so runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) { }
David Kubecka
10/16/2023, 2:16 PMeventLoop
variable is null).eventLoop
dispatcher or I can safely replace it with my own dispatcher (which possibly doesn't implement eventLoop
).Sam
10/16/2023, 2:50 PMDavid Kubecka
10/17/2023, 7:05 AMSam
10/17/2023, 7:10 AMDavid Kubecka
10/17/2023, 7:31 AMsimon.vergauwen
10/17/2023, 7:35 AMLockSupport.park
and it's being undone by LockSupport.unpark
so the eventloop is not responsible for that. The eventloop is meant such that you can return to the caller thread within the coroutine system for context preservation).
Take following example:
suspend fun main() {
println(Thread.currentThread().name) // main
withContext(Dispatchers.Default) {
println(Thread.currentThread().name) // default-worker
}
println(Thread.currentThread().name) // default-worker
}
fun main(): Unit = runBlocking {
println(Thread.currentThread().name) // main
withContext(Dispatchers.Default) {
println(Thread.currentThread().name) // default-worker
}
println(Thread.currentThread().name) // main
}
Thanks to the eventloop the last thread printed in the runBlocking
example is main
Sam
10/17/2023, 7:49 AMeventLoop
is null
, the thread is just parked indefinitely, until the job completion triggers it to unpark.
• If eventLoop
is non-null, the thread is parked only when it runs out of events. If the event loop has events scheduled for the future, the thread is parked until those events are ready. Otherwise, it's parked indefinitely. It can be unparked either by completion of the job or by a new event being dispatched to the event loop.David Kubecka
10/17/2023, 7:55 AM