Coroutines Under the Hood
KOTLIN › Coroutines
What suspend compiles to: continuations, the state machine, context elements, and interception.
Once you can use coroutines, interviewers start asking how they work, and this is where prepared candidates separate themselves. Expect to explain what suspend compiles to, what a Continuation actually is, why a suspended coroutine costs a heap object rather than a thread stack, and how a dispatcher gets control through ContinuationInterceptor. Strong answers derive structured concurrency from Job being a context element rather than treating it as a separate feature, and know the three things suspend does not mean.
What this covers
- suspend is a compiler transformation into continuation-passing style, not a runtime or JVM feature
- Every suspend fun gains a hidden Continuation parameter and returns either the value or COROUTINE_SUSPENDED
- The body becomes a state machine: a label field, a branch per suspension point, and surviving locals promoted to fields
- A suspended coroutine is a heap object, which is why the thread is free and why 100k waiting coroutines are cheap
- The fast path matters: a suspend fun that has its value immediately never allocates a continuation
- CoroutineContext is an immutable set keyed by element type; plus replaces per key, which is why one dispatcher fits
- Job is a context element, and every structured-concurrency guarantee follows from the parent link a builder creates
- A dispatcher implements ContinuationInterceptor, wrapping the continuation so resumeWith dispatches instead of running inline
- CoroutineStart has four modes; a LAZY coroutine nobody starts hangs its parent rather than being ignored
- suspend does not mean background, non-blocking, or parallel: it only makes waiting cheap
Study this topic
- Coroutines Under the Hood explained: the guided lesson
- 16 practice quiz questions
- 15 revision flashcards
- Coroutines Under the Hood interview questions and answers