channel.send() or actor { consumeEach {}} may susp...
# coroutines
channel.send() or actor { consumeEach {}} may suspend on queue full or empty. I wonder how this suspension is implemented under the hood. How the
suspended send
waits until the Queue has more capacity available. Or in other words how the send coroutine is informed that the Queue has capacity available. It is usual although consider a bad practice in Java, to synchronize on a queue monitor and wait for its size to change. Then whatever consuming thread that acquires the monitor will consume some items release the monitor and notify other waiters. I guess that in coroutines, above mechanics is not used since it blocks/sleeps the
thread. It probably works by re-scheduling another
suspend send
coroutine in the executor. Maybe not, maybe it spins lock on the Queue capacity. Does anyone can explain what happens internally?
You should probably read up on how suspend/resume works in general, as those mechanisms are backed by that system. Essentially, calling
or some variant of it will give you a Continuation object. Either you immediately return a result (no suspension occurs), or you return COROUTINE_SUSPENDED, and at a later point call
, which starts up the coroutine again. Presumably
stores the continuation somewhere, and when an item is taken, the continuation is resumed to check if the item can be inserted. The actual mechanics are likely more complicated, but that would be the basics.
I kind of get the first part, the continuation.resumeWith(). The way I visualize coroutines is like a Runnable that gets sent to an executor and that runnable has a reference to the scope where it was launched. When the Runnable reaches the end, it calls back to the original scope and continue execution there. Now, the second part is what I want to know. What you said makes since. However, I would like to see it with my eyes. 🙂 Maybe I should read the code I think is open source right.
yes, all the code is open source. I recommend reading it in an IDE, simply for jumping to called methods. But that's basically how I pulled out the above message 🙂
Yes that's what I usually do but sometimes the decompiled code lose helper things like comments and such. Thanks
You don’t have to decompile it to read it in an IDE, there are source jars available and you can also just clone the coroutines repo and open it directly.
Oh yeah you are right, thanks