Steyrix
Steyrix

Reputation: 3226

How the coroutine knows that it is time to resume/suspend?

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

Answers (1)

Steyrix
Steyrix

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:

  • Thread is a different mechanism, which is linked to the native thread of OS. This is the reason why creating hundreds/thousands of threads is impossible - thread consumes a lot of OS' memory. Coroutine is a user-level abstraction of some worker which does not use excessive amount of memory, since it is not linked to native resources and use resources of JVM heap.
  • Thread gets blocked instead of suspending and dispatching the job to another thread.
  • Thread cannot be used until its work completes.
  • Thread is asynchrounous whereas coroutines are sequentional. According to the previous point, a thread performs some kind of work asynchronously and cannot be used. On the other hand a coroutine, being a user-friendly abstraction, is executed on the thread and after it gets suspended, the next one gets executed on the same thread. (This point answers to "How the thread deal with the coroutines states and decides, which one to run?")

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

Related Questions