I'm trying to understand how Kotlin coroutines work and why they are said to be more efficient than threads.
As I understand it so far:
- when a
suspend
function is paused, under the hood it voluntarily gives control back to the caller, which in turn does the same thing until we reach some kind of "root" call that manages everything, e.g. the coroutine scheduler - the scheduler checks which paused functions are ready to resume and tells them to continue
- it is basically something like a queue with a thread pool
Is this roughly correct?
My concern is:
If inside a suspending function we call a classic Java API that blocks for I/O, it won't automagically make the code more efficient if we simply wrap it in a coroutine, because it would not cooperate with the scheduler, right? Not to mention CPU-intensive tasks.
i.e. it's not like the Node event loop where all I/O is asynchronous by default and is off-loaded to epoll
or something similar, it's just a big thread pool under the hood?