Coroutines Internals: How The Sausage is Made
summary
Kotlin suspendable functions compile by adding a Continuation parameter and becoming a suspend functions → state machine that returns Any? (or the sentinel COROUTINE_SUSPENDED) and stores per-state locals inside a generated continuation; continuations wrap caller continuations to continuations wrap to form call stack so resumptions call resumeWith down the chain. Dispatching is a continuation interceptor implemented by dispatchers: main uses an Android Handler, default and IO are backed by the same thread pool (IO starts at 64 threads) and support limited parallelism; examples include reimplementing delay with ScheduledThreadPool and using suspendCancellableCoroutine; compiler optimizations can elide locals and duplicate try/catch across states.
AI-written summary · about
chapters (18)
- 0:00Introduction
- 1:45What makes coroutines lightweight
- 3:09Callback and threading problems
- 5:15Coroutines vs callbacks
- 6:19Delay with continuations
- 8:51Compiler transforms suspendable functions
- 10:37State machines and continuations
- 14:27Preserving state across suspensions
- 16:13Debugging and optimizations
- 17:35Loops in state machines
- 20:04Try-catch in suspendable functions
- 20:47Call stack with continuations
- 24:40Threading with interceptors
- 27:07Dispatchers implementation
- 29:37Main dispatcher on Android
- 32:50Default and IO dispatchers
- 35:20Shared thread pool behavior
- 37:04Recap and key takeaways








