Going through coroutines and the example provided refers to the coroutine launched by runBlocking() as the parent coroutine. Does the term parent refer to the first coroutine started? Code shows that there are three coroutines each of which are individual. Are the other two coroutines contained within the first? Is there a hierachy?
private var zeroTime = System.currentTimeMillis()
fun log(message:Any?){
println("${System.currentTimeMillis() - zeroTime}" + "[${Thread.currentThread().name}] $message")
}
fun main() = runBlocking{
log("The first, parent, coroutine starts")
launch{
log("The second coroutine starts and is ready to be suspended")
delay(100.milliseconds)
log("The second coroutine is resumed")
}
launch{
log("The third coroutine can run in the meantime")
}
log("The first coroutine has launched two more coroutines")
}
Yes, there's a hierarchy. Any coroutines launched inside the runBlocking
code block will be linked as children of the runBlocking
task. The same is broadly true for any coroutine launched inside another coroutine.
What implications does it have? Most importantly, the runBlocking
function will always wait for the child coroutines to finish their work. In your example, that's how your main()
function knows it should continue waiting while the inner "second coroutine" is performing its 100 millisecond delay. More generally, a parent coroutine will never be considered finished while it has child coroutines that aren't yet finished, and anything that's waiting for the parent coroutine's completion will also need to wait for the children.
How does it work? The hierarchy is formed using a coroutine scope. When you call a builder function like runBlocking
, a coroutine scope is created. If you look at the launch
function's signature, you'll see that it takes this CoroutineScope
as its receiver. The scope contains information about the parent coroutine, which allows Kotlin to link the two tasks.
The hierarchy imposes a couple of other rules, too, but you won't see them in your example code because you don't have any errors or cancellations.