— Coroutines under the hood Agenda This talk is about coroutines implementation and its implications Part I. The importance of being asynchronous • Remote calls • Microservices • Interactions Threading • Thread per connection • Footprint (~1M stack, 1M VM metadata) • Scalability Callbacks Reactive programming https://medium.com/netflix-techblog/reactive-programming-in-the-netflix-api-with- rxjava-7811c3a1496a Reactive programming Lesser of two evils Part II. Continuations A continuation is a representation of the computation Continuations in Kotlin suspend fun asyncSum(initial: Int) { println ( "Started execution" ) val value = asyncValue () println ( "Sum: ${ initial + value }" ) } fun main() { ::asyncSum. startCoroutine (20) println ( "Back to main" ) computation .resumeWith(22) } Started execution Continuations in Kotlin suspend fun asyncSum(initial: Int) { println ( "Started execution" ) val value = asyncValue () println ( "Sum: ${ initial + value }" ) } fun main() { ::asyncSum. startCoroutine (20) println ( "Back to main" ) computation .resumeWith(22) } Started execution Back to main Continuations in Kotlin suspend fun asyncSum(initial: Int) { println ( "Started execution" ) val value = asyncValue () println ( "Sum: ${ initial + value }" ) } fun main() { ::asyncSum. startCoroutine (20) println ( "Back to main" ) computation .resumeWith(22) } Started execution Back to main Sum: 42 How could it work? Suspension points suspend fun asyncSum(initial: Int) { // State 1 println ( "Started execution" ) val value = computeAsync () // State 2 val sum = initial + value println ( "Sum: $ sum " ) } CPS transformation interface Continuation< in T> { val context : CoroutineContext fun resumeWith(result: Result<T>) } fun asyncSum(..., continuation: Continuation<*>) { println ( "Started execution" ) val value = asyncValue () println ( "Sum: ${ initial + value }" ) } CPS transformation fun asyncSum(initial: Int, callback: () -> Unit) { println ( "Started execution" ) asyncValue { value -> println ( "Sum: ${ initial + value }" ) callback() } } CPS. State machine fun asyncSum(initial: Int, c: Continuation<*>) { } val me = c as? AsyncSumCont ?: AsyncSumCont(c) 1 -> { val value = me. valueOrThrow println ( "Sum: ${ initial + value }” ) me .caller. resumeWith(Unit) } 0 -> { println ( "Started execution” ) asyncValue(me) } when (me. label ) { fun asyncSum(initial: Int, c: Continuation<*>) { when (me. label ) { 0 -> { println ( "Started execution” ) asyncValue(me) } } } CPS. State manipulation fun asyncSum(initial: Int, c: Continuation<*>) { when (me. label ) { 0 -> { println ( "Started execution" ) me. label = 1 me. initial = initial asyncValue(me) } } } State manipulation. Spilling class AsyncSumCont() : Continuation<Int> { val caller : Continuation<Unit> val label : Int val initial : Int val value : Int override fun resumeWith(value: Int) { value = value asyncSum( initial , this ) } } State manipulation. Resume