Reputation: 3226
Let's say we have a job A and a job B (not kotlin's Job
, just some kind of work).
I am told that coroutines can suspend and thus the underlying thread used by A will not be blocked and can be used for B, while A suspends.
Let's say, that A performs some kind of downloading data from server. How does A perform such work, while being suspended (if it gets suspended)? How does it know that it is time to resume and hold the thread again? How the thread deal with the coroutines states and decides, which one to run?
I guess it uses good old wait/notify mechanism under the hood, however it is unclear for me, how the example download can happen while the thread is used for another work already?
Upvotes: 2
Views: 1170
Reputation: 3226
How does the coroutine perform work, while being suspended (if it gets suspended)?
After some research I found out, that when the coroutine suspends it actually gets dispatched to another thread (as was mentioned by bylazy), in which it continues execution.
How does it know that it is time to resume and hold the thread again?
Taking the example from the question, the download will be dispatched to a separate thread of the implicit threadpool (which was mentioned by Tenfour04) and will use continuation object to resume on former thread.
At the same time, the former thread remains available for another work. Whereas Java's Thread
has differences that explain why coroutines' performance is higher:
So the coroutines make the better and more efficient use of threads, taking care of dispatching, reusing resources, managing thread pool and etc.
The sources I used:
Upvotes: 4