3

Coroutine has two types. Stackful and Stackless. And Kotlin coroutine is stackless coroutine.

On the other hand, once a method gets called it is stacked on the memory. And we can do recursive calling with method.

And in Kotlin, all I need to do is adding suspend keyword for the methods that are called in coroutine context.

It doesn't have a stack, then how does it work?

What I am guessing is, since coroutine Object belongs to a certain thread, the thread have them. Let's say, yes it is. Then how does it work under the hood?

1 Answer 1

9

Kotlin coroutines are actually a hybrid between stackful and stackless. For every function invocation there is a regular Java stack frame. When you invoke a suspend fun from a suspend fun, the JVM stack grows the usual way, and if the call returns without any suspension happening, the stack unwinds also in the common JVM way.

Things become different when a function suspends. At that point, the Java methods return and the JVM stack unwinds. However, while the call chain was being built up, another, on-heap structure was being formed: a linked list of Continuation objects. Every suspend fun invocation creates another such object, which you can think of as a stack frame (it contains the values of all the local variables), but implemented at the bytecode level, as a regular Java object.

This Continuation chain is the "stackless" aspect of Kotlin coroutines. When you resume a continuation, you'll enter the innermost function call (containing the location where the function suspended). When that function wants to return, it won't return the normal way, instead it will resume its caller's continuation. This will repeat in the caller, and so as you travel up the suspend fun call stack, you'll be also traveling down the JVM call stack: the JVM stack grows as the suspendable functions return.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Marko, thanks for the descriptive answer. I want to dig deeper. Can you give the link to the resource that can help?
You can check out this talk of mine from KotlinConf 2017 where I show some internal implementation details with an actual example of this mechanism youtube.com/watch?v=YrrUCSi72E8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.