Skip to content

Instantly share code, notes, and snippets.

@davibe
Created November 13, 2017 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davibe/5c933a31f19bfbc92b728e3aab61463e to your computer and use it in GitHub Desktop.
Save davibe/5c933a31f19bfbc92b728e3aab61463e to your computer and use it in GitHub Desktop.
Example of structured concurrency in Kotlin
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.Channel
import java.util.*
/*
* Structured concurrency means that child co-routines should die when their father dies
* http://libdill.org//structured-concurrency.html
*
* In kotlin in order to have parent->child relationship you need to explicitly pass
* the coroutineContext to the child coroutine.
*/
fun main(args: Array<String>) = runBlocking<Unit> {
println("Main: context ${coroutineContext}")
val father = launch(coroutineContext) {
println("Father: context ${coroutineContext}")
launch(coroutineContext) {
println("Child: context ${coroutineContext}")
do {
println("Child: is alive")
delay(1000)
} while (true)
}
// Father is not actually dead until `father.cancel()` because the child
// is keeping it alive. Here we could also use
// coroutineContext.cancel() or coroutineContext.cancelChildren()
}
delay(3000)
print("Main: killing father")
father.cancel()
delay(3000)
print("Main: is done")
}
@davibe
Copy link
Author

davibe commented Nov 13, 2017

output:

Main: context [BlockingCoroutine{Active}@66d33a, BlockingEventLoop@7cf10a6f]
Father: context [StandaloneCoroutine{Active}@35f983a6, BlockingEventLoop@7cf10a6f]
Child: context [StandaloneCoroutine{Active}@6cd8737, BlockingEventLoop@7cf10a6f]
Child: is alive
Child: is alive
Child: is alive
Main: killing father
Main: is done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment