Coroutines are a completely separate thing from any scheduling policy that you describe. A coroutine is basically a call chain of suspend fun
s. Suspension is totally under your control: you just have to call suspendCoroutine
. You'll get a callback object so you can call its resume
method and get back to where you suspended.
Here's some code where you can see that suspension is a very direct and trasparent mechanism, fully under your control:
import kotlin.coroutines.*
import kotlinx.coroutines.*
var continuation: Continuation<String>? = null
fun main(args: Array<String>) {
val job = GlobalScope.launch(Dispatchers.Unconfined) {
while (true) {
println(suspendHere())
}
}
continuation!!.resume("Resumed first time")
continuation!!.resume("Resumed second time")
}
suspend fun suspendHere() = suspendCancellableCoroutine<String> {
continuation = it
}
All the code above executes on the same, main thread. There is no multithreading at all going on.
The coroutine you launch
suspends itself each time it calls suspendHere()
. It writes the continuation callback to the continuation
property, and then you explicitly use that continuation to resume the coroutine.
The code uses the Unconfined
coroutine dispatcher which does no dispatching to threads at all, it just runs the coroutine code right there where you invoke continuation.resume()
.
With that in mind, let's revisit your diagram:
GlobalScope.launch { <---- (A)
val y = loadData() <---- (B) // suspend fun loadData()
println(y) <---- (C)
delay(1000) <---- (D)
println("completed") <---- (E)
}
- Kotlin has a pre-defined
ThreadPool
at the beginning.
It may or may not have a thread pool. A UI dispatcher works with a single thread.
The prerequisite for a thread to be the target of a coroutine dispatcher is that there is a concurrent queue associated with it and the thread runs a top-level loop that takes Runnable
objects from this queue and executes them. A coroutine dispatcher simply puts the continuation on that queue.
- At
(A)
, Kotlin starts executing the coroutine in the next available free thread (Say Thread01
).
It can also be the same thread where you called launch
.
- At
(B)
, Kotlin stops executing the current thread, and starts the suspending function loadData()
in the next available free thread (Thread02
).
Kotlin has no need to stop any threads in order to suspend a coroutine. In fact, the main point of coroutines is that threads don't get started or stopped. The thread's top-level loop will go on and pick another runnable to run.
Furthermore, the mere fact that you're calling a suspend fun
has no significance. The coroutine will only suspend itself when it explicitly calls suspendCoroutine
. The function may also simply return without suspension.
But let's assume it did call suspendCoroutine
. In that case the coroutine is no longer running on any thread. It is suspended and can't continue until some code, somewhere, calls continuation.resume()
. That code could be running on any thread, any time in the future.
- When
(B)
returns after execution, Kotlin continues the coroutine in the next available free thread (Thread03
).
B
doesn't "return after execution", the coroutine resumes while still inside its body. It may suspend and resume any number of times before returning.
(C)
executes on Thread03
.
- At
(D)
, the Thread03
is stopped.
- After 1000ms,
(E)
is executed on the next free thread, say Thread01
.
Again, no threads are being stopped. The coroutine gets suspended and a mechanism, usually specific to the dispatcher, is used to schedule its resumption after 1000 ms. At that point it will be added to the run queue associated with the dispatcher.
For specificity, let's see some examples of what kind of code it takes to dispatch a coroutine.
Swing UI dispatcher:
EventQueue.invokeLater { continuation.resume(value) }
Android UI dispatcher:
mainHandler.post { continuation.resume(value) }
ExecutorService dispatcher:
executor.submit { continuation.resume(value) }