https://kotlinlang.org logo
v

VIVEK SHAH

12/22/2022, 1:29 PM
Hi All I was trying to wrap my head around how exactly launch coroutine builder implements async code on a single thread in JVM. Is there a default scheduler that monitors the number of incomplete coroutines and launches them one by one on Single thread? I have attached the sample code for your reference. Please note all the coroutines are being run on the Main thread asynchronously. Since there is no suspendable computation within coroutines created by launch i don't expect any concurrency. I have tested it using delay in attached code can also show concurrent behaviour as well Output is as follows and matches expectations as well
BEFORE launching async tasks in Thread main
AFTER launching async tasks in Thread main
Task 1 in Thread main
Task 2 in Thread main
s

Sam

12/22/2022, 1:53 PM
You can probably find some explanation in the docs for
runBlocking
. That's what provides the scheduler, and yes, it works pretty much the way you describe. It's referred to as an "event loop", because it loops over the incomplete coroutines and runs them one by one.
u

uli

12/23/2022, 12:15 AM
And it is not much different from a multi threaded dispatcher. Dispatchers hold a queue of coroutines ready to run. And each thread (of one or many) grabs a new coroutine when it becomes idle or if it was already idle and a new coroutine is queued to the empty queue.
v

VIVEK SHAH

12/23/2022, 1:06 AM
Thanks. Makes sense. I was trying to connect from executor style implementation where a thread is blocked and cannot be reused until a task is finished. But the catch here it seems is implementation of an event loop which makes non blocking code on jvm executed on same thread
2 Views