The Analogy: One Baker, Several Timed Ovens
A small artisan bakery opens before dawn with a single baker on duty and a row of four ovens along the back wall, each with its own mechanical timer. The morning order calls for rye, baguettes, rolls, and a fruit loaf, and every one of them needs a long stretch in the oven during which nothing useful can be done to it. If the baker had to give each loaf their undivided attention from the moment it went in until the moment it came out, the shop could never fill a morning order: four long bakes done strictly one after another would run past lunchtime.
So the baker works the way any sensible baker does. They slide the rye into oven one and wind its timer to twenty-five minutes, and instead of standing there watching it, they immediately move to oven two, load the baguettes, and set that timer to forty minutes. Loading a tray and winding a timer takes only a few seconds; the long wait belongs to the timer, not to the baker. While the timers tick, the baker is free to load the next oven, knead the next batch, or wipe down the bench. When a timer rings the baker returns to that oven, pulls the tray, and carries on. Because the timers were set for different lengths, they ring in a predictable order -- the shortest bake finishes first -- and the baker attends to whichever oven is calling.
There is one firm rule in this bakery, laid down by the head baker: you may not lock up and go home while any timer is still ticking. The morning shift is not over when the last tray goes in; it is over when the last tray comes out and every oven is empty and cold. If a baker has started four bakes, the shift owns those four bakes, and the baker must stay until all four are accounted for. This single rule is what keeps loaves from being abandoned in a warm oven overnight, and it means that when the shift is finally reported complete, you can trust that nothing it started is still secretly running.
The failure that ruins a morning is the nervous relief baker who does not trust the timers. They slide the rye in, then plant themselves in front of oven one and refuse to move until the rye is done, ignoring the three cold ovens behind them. Only when the rye is out do they load the baguettes, and again they stand and stare. Every bake that could have overlapped is now done strictly in turn, and a morning's work that should have finished by the overlap of timers instead stretches into the afternoon. The ovens were never the bottleneck; the baker's refusal to step away during the wait was. That baker has turned a kitchen built for concurrency back into a queue of one.
Syntax or Core Structure
A coroutine is a computation that can suspend -- pause itself and give the thread back -- and later resume where it left off. The suspension is the timer winding: the baker (the thread) is released to do other work while the wait elapses. You start coroutines inside a scope. runBlocking bridges ordinary blocking code to the coroutine world by creating a scope and blocking its own thread until every coroutine started inside finishes. launch starts a coroutine that returns no value. delay suspends the current coroutine without blocking the thread.
import kotlinx.coroutines.*
fun main() = runBlocking {
println("shift starts")
launch {
delay(200L)
println("rye out at 200")
}
launch {
delay(100L)
println("rolls out at 100")
}
println("both ovens loaded")
}
Output:
shift starts
both ovens loaded
rolls out at 100
rye out at 200
Read the order carefully, because it surprises everyone at first. launch does not run its body on the spot; it schedules a coroutine and returns immediately, so both ovens are loaded before either bake begins. "both ovens loaded" therefore prints before any loaf comes out. Only when the main coroutine reaches the end of the runBlocking block and has nothing left to do does it wait for its children, letting the two launched coroutines run. Each hits its delay and suspends; the 100 ms timer rings before the 200 ms timer, so "rolls out at 100" always precedes "rye out at 200". The ordering is fixed by the delay amounts, not by the order the ovens were loaded. And runBlocking does not return until both children finish -- that is the head baker's rule, enforced by the language.
Technical Depth: Scopes, Jobs, and Waiting
The builders and what they return
Every coroutine is started by a builder, and the builder decides both what you get back and how it relates to the surrounding scope.
| Builder | Returns | Blocks the thread | Typical use |
|---|---|---|---|
| runBlocking | the block's result | yes, until children finish | bridging main or tests into coroutines |
| launch | a Job | no | fire-and-forget work with no result |
| async | a Deferred of T | no | concurrent work that produces a value |
| coroutineScope | the block's result | no, suspends instead | grouping children inside a suspend function |
The distinction that matters most for correctness is blocking versus suspending. runBlocking holds its thread hostage until everything inside completes, which is why it belongs at the very edge of a program -- main, or a test -- and almost never in library code. launch and async do not block; they schedule work and hand back a handle. coroutineScope suspends the caller rather than blocking a thread, so it is the tool you reach for inside other suspending code.
delay suspends; Thread.sleep blocks
The single most common coroutine bug is reaching for Thread.sleep where delay was meant. delay winds the timer and steps away; Thread.sleep is the nervous baker standing at the oven. On a single thread the difference is stark: sleeping serialises work that delaying would overlap.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
println("bake begins")
delay(50L)
println("bake ends")
}
println("job started, is it done yet? " + job.isCompleted)
job.join()
println("after join, is it done now? " + job.isCompleted)
}
Output:
bake begins
job started, is it done yet? false
after join, is it done now? true
bake ends
The order rewards a careful trace. launch schedules the coroutine and returns the Job at once, so the main coroutine keeps running and reaches the isCompleted check first; but launched work does get a chance to run up to its first suspension point, printing "bake begins" before control returns to main. At the check the job has only suspended on delay, so isCompleted is false. Then join suspends main until the job finishes. Here is the subtle part: the two lines printed after the delay elapses -- "after join" from main and "bake ends" from the job -- come out with the job's own resumption first is not what happens; main is resumed by join returning, and it prints "after join" then the coroutine's own remaining line "bake ends" trails. The exact interleave of those final two is fixed by the runtime's resume order and is stable in runBlocking's single thread.
coroutineScope waits for all its children
coroutineScope builds a scope that does not return until every coroutine launched inside it has completed. It is structured concurrency in one function: the scope owns its children.
import kotlinx.coroutines.*
suspend fun bakeBatch() = coroutineScope {
launch { delay(30L); println("tray A done") }
launch { delay(10L); println("tray B done") }
println("both trays in")
}
fun main() = runBlocking {
bakeBatch()
println("batch reported complete")
}
Output:
both trays in
tray B done
tray A done
batch reported complete
"both trays in" prints first because launch schedules without running. The two trays then finish in delay order, B (10 ms) before A (30 ms). Crucially, "batch reported complete" prints last: coroutineScope did not return control to main until both launched children were done. If bakeBatch had used a detached scope instead, that final line could have printed while trays were still baking -- the head baker's rule broken.
Real World Example: Dispatching a Morning Batch
This program runs the bakery's morning batch. Three bakes are launched together inside a coroutineScope, each with a distinct bake time, and a shared counter tracks how many have come out of the oven. The scope guarantees that the batch is not reported complete until every bake is pulled.
import kotlinx.coroutines.*
var finished = 0 // shared mutable state at the top level
suspend fun runMorningBatch() = coroutineScope {
val bakes = listOf("rolls" to 5L, "rye" to 15L, "baguette" to 25L)
for ((name, ms) in bakes) {
launch {
delay(ms)
finished++
println("pulled " + name + ", finished count now " + finished)
}
}
println("all " + bakes.size + " bakes dispatched")
}
fun main() = runBlocking {
runMorningBatch()
println("batch complete, total finished: " + finished)
}
Output:
all 3 bakes dispatched
pulled rolls, finished count now 1
pulled rye, finished count now 2
pulled baguette, finished count now 3
batch complete, total finished: 3
The first line is the scheduling surprise you have now seen twice: all three launch calls only schedule coroutines, so "all 3 bakes dispatched" prints before any bake finishes. The loop hands each coroutine its own name and ms through destructuring of the Pair, and the three then suspend on their delays.
The three "pulled" lines come out in ascending delay order -- 5 ms, then 15 ms, then 25 ms -- because the shortest timer rings first, exactly as the ovens did in the analogy. The counter reads 1, 2, 3 in step, and it does so cleanly because on runBlocking's single thread each coroutine runs from its resume point to its next suspension without being interrupted. Nothing else touches finished in the middle of an increment.
The final line proves structured concurrency did its job: "batch complete, total finished: 3" prints only after coroutineScope has waited for all three children. If the function had launched into a detached, long-lived scope, runMorningBatch could have returned with the count still at zero and the loaves still baking.
The genuine design flaw is that finished++ is a read-modify-write on shared mutable state, and it is correct here purely by accident of confinement. Everything runs on one thread under runBlocking, so the increments cannot interleave. Move these coroutines onto a multi-threaded dispatcher such as Dispatchers.Default and the same line becomes a data race: two coroutines can read the same value, each add one, and each write back the same result, silently losing a count. On top of that, a top-level var makes the function non-reentrant -- two overlapping batches would corrupt each other's total. A correct version confines the count to the scope and uses an atomic or a Mutex, so the program's correctness does not depend on which dispatcher it happens to run on.
Common Mistakes
- Calling
Thread.sleepinside a coroutine. Sleeping blocks the whole thread, freezing every other coroutine sharing it. Usedelay, which suspends and hands the thread back. The nervous baker at one oven isThread.sleep; the timer isdelay.
- Assuming
launchruns its body immediately.launchschedules a coroutine and returns at once. Code written right after alaunchruns before the launched body, which is why "loaded" lines print before "done" lines. Do not rely on launched work having happened by the next statement.
- Expecting a value back from
launch.launchreturns aJob, not a result. If you need a computed value, useasyncandawait. Reading a variable the launched coroutine was supposed to set, without joining first, reads it too early.
- Using
GlobalScope.launch. Coroutines started inGlobalScopeare not children of any structured scope, so nothing waits for them and nothing cancels them. They leak. Launch into a scope you own instead.
- Leaving
runBlockingin production code.runBlockingblocks its calling thread until completion, defeating the purpose of coroutines. Keep it at the true edge --mainand tests -- and suspend everywhere else.
- Sharing mutable state without synchronization.
count++from several coroutines is a data race on any multi-threaded dispatcher. Code that works underrunBlockingcan break the moment it moves toDispatchers.Default. Use an atomic, aMutex, or confine the state.
- Swallowing
CancellationException. Catching it in a broadtry/catchand not rethrowing breaks cooperative cancellation, so a cancelled coroutine keeps running. Let it propagate, or rethrow it after cleanup.
- Calling a
suspendfunction from ordinary code. Asuspendfunction can only be called from another suspend function or a coroutine builder. Calling it from a plain function does not compile; you need a scope such asrunBlockingorcoroutineScope.
- Believing coroutines are threads. Many coroutines multiplex onto a few threads. A thousand coroutines does not mean a thousand threads, and blocking one coroutine's thread starves the others assigned to it.
Best Practices
- Reach for
delay, neverThread.sleep, inside any coroutine, so waiting suspends rather than blocks.
- Launch coroutines into a scope you own --
coroutineScope, aCoroutineScopetied to a lifecycle -- and never intoGlobalScope.
- Keep
runBlockingat the program's edge only; write the rest assuspendfunctions so callers stay non-blocking.
- Use
launchfor fire-and-forget work andasync/awaitwhen a coroutine must produce a value.
- Wrap a group of related coroutines in
coroutineScopeso the group completes only when all its children do.
- Protect any state shared across coroutines with an atomic, a
Mutex, or confinement; do not rely on a dispatcher happening to be single-threaded.
- Let
CancellationExceptionpropagate; if you must catch broadly, rethrow it so cancellation still works.
- Prefer
joinon aJob(orawaiton aDeferred) over sprinklingdelayto "wait long enough" for other coroutines.
Practice Exercises
- Write a
runBlockingblock that launches three coroutines with delays of 300, 100, and 200 milliseconds, each printing its name when it finishes, plus a line after the launches. Predict the exact print order before running, then confirm it.
- Take a function that bakes three items strictly in turn using
Thread.sleep, and rewrite it withlaunchanddelayinside acoroutineScopeso the bakes overlap. Show that the total wall time drops from the sum of the waits to the longest single wait.
- Start from the
finished++batch in this lesson, move the coroutines ontoDispatchers.Defaultwith a much larger count of increments, and demonstrate that the final total is sometimes wrong. Then fix it with an atomic and show the total is now always correct.
- Write a
suspend fun greet()that delays then prints, and try to call it directly frommainwithout a builder. Record the compile error, then wrap the call inrunBlockingand explain why that fixes it.