The Analogy: Routing Work to the Right Hospital Department
A large hospital routes every incoming task to the department staffed for it, and three departments make the point. There is a small surgical team, a large nursing ward, and a single reception desk at the front door. Each is sized and equipped for one particular kind of work, and the hospital runs smoothly only because tasks are sent to the department built to handle them.
The surgical team is deliberately small -- a handful of highly focused specialists -- because surgery is intense, uninterrupted, hands-on work, and there is no point staffing more surgeons than there are operating rooms. This is the department you send demanding work that needs full concentration and keeps whoever is doing it fully occupied from start to finish. Adding more surgeons than rooms would not speed anything up; the constraint is the rooms, which mirror the fixed number of processor cores a machine actually has.
The nursing ward, by contrast, is large -- dozens of nurses -- because most of a nurse's task is spent waiting. Waiting on a lab result, waiting on a drip to finish, waiting for a patient to respond. A nurse who is waiting is not doing hard work, merely occupying a slot, so it pays to have many of them: while dozens wait, the ward as a whole keeps flowing. The reception desk is the opposite extreme, a single clerk who must never be tied up, because the instant reception is blocked the public face of the hospital freezes and the queue backs into the street. Travelling with every task is a chart that names which department it belongs to, a case label, and who to call if something goes wrong.
The failures are all misrouting. Send a scarce surgeon to sit and wait three hours for a lab result and you have burned one of your few specialists on pure waiting while the operating rooms stand idle. Do the reverse -- hand the single reception clerk an hour of heads-down paperwork -- and the front desk is unmanned, the queue swells, and every new arrival is stuck. The departments are not interchangeable. The whole purpose of routing is to match the kind of work to the crew built for it, and nearly every serious slowdown traces back to a task sent to the wrong department.
Syntax or Core Structure
A dispatcher decides which thread or pool of threads a coroutine runs on -- which department the work is sent to. Dispatchers.Default is the surgical team, sized to the CPU cores for heavy computation. Dispatchers.IO is the nursing ward, a large elastic pool for blocking waits. withContext moves the enclosed block onto a chosen dispatcher, runs it, and returns its result, resuming the caller where it left off.
import kotlinx.coroutines.*
fun main() = runBlocking {
println("on the main coroutine")
val total = withContext(Dispatchers.Default) {
var s = 0
for (i in 1..100) s += i
s
}
println("sum 1..100 = " + total)
println("back after withContext")
}
Output:
on the main coroutine
sum 1..100 = 5050
back after withContext
The block inside withContext(Dispatchers.Default) is sent to the CPU-bound pool, where it adds the numbers 1 through 100 and yields 5050 as the last expression. withContext returns that value into total, and the coroutine resumes on its original context to print the result. The three lines print strictly in order because withContext is a suspending call that does not return until its block completes: it is a round trip to another department and back, not a fire-and-forget. Notice what is not printed here -- the thread name -- because which specific thread in the pool ran the sum is an implementation detail that varies from run to run, while the computed value 5050 is fixed.
Technical Depth: Context Is a Set of Elements
The standard dispatchers
Kotlin ships a handful of dispatchers, each a department with a purpose. Choosing the right one is the difference between a smooth hospital and a jammed one.
| Dispatcher | Backing threads | Send it |
|---|---|---|
| Default | pool sized to CPU cores | CPU-bound computation |
| IO | large elastic pool | blocking I/O and waits |
| Main | the single UI thread | code that touches UI state |
| Unconfined | no threads of its own | advanced cases only, rarely |
The rule is simple: heavy computation goes to Default, blocking waits go to IO, and Main stays free for the interface. Unconfined starts in the caller's thread and resumes wherever its suspension happened to complete, which makes it unpredictable and unsuitable for almost all application code.
A context is elements combined
A CoroutineContext is not just a dispatcher; it is a set of elements, each keyed by its type. The dispatcher is one element. So is the Job that governs lifecycle, the CoroutineName used in debugging, and any CoroutineExceptionHandler. You combine them with +, and you look one up by its key.
| Element | What it carries |
|---|---|
| Job | lifecycle and cancellation |
| CoroutineDispatcher | which thread or pool runs the code |
| CoroutineName | a debug label for the coroutine |
| CoroutineExceptionHandler | handling for uncaught exceptions |
import kotlinx.coroutines.*
fun main() = runBlocking {
launch(CoroutineName("worker-A")) {
val name = coroutineContext[CoroutineName]?.name
println("running as " + name)
}.join()
println("done")
}
Output:
running as worker-A
done
The launch is given a CoroutineName element in its context. Inside, coroutineContext[CoroutineName] looks that element up by key and reads its name, printing "running as worker-A". The join makes the parent wait, so "done" prints after. The name is a fixed string we supplied, so it is fully deterministic, unlike the underlying thread.
Context is inherited and scoped
A child coroutine inherits its parent's context, and withContext overrides only the elements you pass, for the duration of its block. Outside the block, the original context is back in force.
import kotlinx.coroutines.*
fun main() = runBlocking(CoroutineName("root")) {
val outer = coroutineContext[CoroutineName]?.name
val inner = withContext(CoroutineName("inner")) {
coroutineContext[CoroutineName]?.name
}
val afterInner = coroutineContext[CoroutineName]?.name
println("outer=" + outer)
println("inner=" + inner)
println("afterInner=" + afterInner)
}
Output:
outer=root
inner=inner
afterInner=root
The runBlocking scope carries the name "root", so outer reads "root". Inside withContext(CoroutineName("inner")) the name element is overridden, so inner reads "inner". The moment the block ends, the override is gone and afterInner reads "root" again. This scoping is exactly what makes withContext safe for switching dispatchers: it changes the context only within its braces and restores it afterwards.
Combining a dispatcher and a name
Because a context is a set of elements, you can supply several at once by adding them with +. The dispatcher and the name coexist in the same context: the code runs on the dispatcher you chose and carries the label you gave it.
import kotlinx.coroutines.*
fun main() = runBlocking {
val result = withContext(Dispatchers.Default + CoroutineName("calc")) {
val label = coroutineContext[CoroutineName]?.name
val product = (1..5).fold(1) { acc, n -> acc * n }
label + " computed " + product
}
println(result)
}
Output:
calc computed 120
The single context Dispatchers.Default + CoroutineName("calc") carries two elements. The block runs on the Default pool and can still read its name back through coroutineContext[CoroutineName], which returns "calc". The product of 1 through 5 is 120, so the assembled line is "calc computed 120". This is the everyday shape of context: pick the department with the dispatcher, and attach a label for debugging, both in one + expression.
Real World Example: A Report Pipeline
This program builds a small report. It first loads records with a blocking-style read, correctly sent to Dispatchers.IO, and then aggregates them into a summary line. The aggregation is CPU-bound work -- looping and comparing -- and where it runs is the point of interest.
import kotlinx.coroutines.*
suspend fun loadRecords(): List<Int> = withContext(Dispatchers.IO) {
delay(10L) // stand-in for a blocking read
listOf(3, 1, 4, 1, 5, 9)
}
suspend fun summarize(): String = withContext(Dispatchers.IO) {
val records = loadRecords()
var sum = 0
var max = records[0]
for (r in records) { // CPU-bound aggregation, left on IO
sum += r
if (r > max) max = r
}
"count=" + records.size + " sum=" + sum + " max=" + max
}
fun main() = runBlocking {
println("report starting")
println(summarize())
println("report done")
}
Output:
report starting
count=6 sum=23 max=9
report done
The pipeline runs in clear sequence. main prints its banner, calls summarize, which itself calls loadRecords to fetch the six numbers, then folds them into a count, a sum, and a maximum. The list is fixed at 3, 1, 4, 1, 5, 9, so the results are always the same: six records, a sum of 23, and a maximum of 9.
The values are deterministic even though the threads are not. Which specific pool thread executed the load or the loop varies between runs, which is why the program prints the computed figures and never a thread name. Printing Thread.currentThread().name here would produce output that changed from run to run and could never be verified.
Sending the load to Dispatchers.IO is the right call: a blocking read is a waiting task, and the IO pool is the large nursing ward built for waiting. The direct style of withContext also keeps the code readable -- load, then aggregate, then format, top to bottom.
The genuine design flaw is that the CPU-bound aggregation runs on Dispatchers.IO too, because summarize wraps its entire body in withContext(Dispatchers.IO). Looping and comparing is heads-down computation, the surgical team's work, and it should switch to Dispatchers.Default for the aggregation while keeping only the blocking read on IO. Leaving CPU work on the IO pool means that under load, heavy loops occupy threads meant for blocking waits, and the elastic IO pool can balloon or starve genuine I/O tasks of a slot. On top of that, loadRecords re-wraps in withContext(Dispatchers.IO) while already on IO, a redundant switch that does nothing. A correct pipeline reads on IO and computes on Default, matching each phase to the department built for it.
Common Mistakes
- Running CPU-bound work on
Dispatchers.IO. The IO pool is for waiting tasks. Heavy loops and computation belong onDispatchers.Default, which is sized to the cores. Leaving compute on IO can exhaust the pool meant for real blocking calls.
- Running blocking calls on
Dispatchers.Default. A blocking JDBC or file call ties up a scarce Default thread that a CPU task needed. Blocking waits belong onIO, which has slack for threads that mostly sit idle.
- Blocking the
Maindispatcher. Long work on the UI thread freezes the interface. Move it off withwithContext(Dispatchers.Default)and letMainstay free to serve the interface.
- Treating
withContextas if it starts a new coroutine.withContextsuspends the current coroutine and switches context; it does not add concurrency. For concurrent work you still needlaunchorasync.
- Relying on
Dispatchers.Unconfined. It resumes on whatever thread completed the last suspension, so its threading is unpredictable. It is an advanced tool, not a sensible default for application code.
- Printing or asserting on thread names. Which pool thread runs a block varies between runs. Depending on
Thread.currentThread().namegives flaky behaviour and non-reproducible output; depend on computed values instead.
- Overriding the
Jobwhen combining context. Passing a freshJobinto a child context detaches it from structured concurrency, so cancellation and errors stop propagating. Override only the elements you actually mean to change, such as the dispatcher or name.
- Leaking custom dispatchers. A dispatcher built from an executor or
newFixedThreadPoolContextholds real threads that must be closed. Prefer the standard dispatchers, and if you must build one, close it when done.
- Assuming a child picks its own dispatcher. A child coroutine with no dispatcher specified inherits the parent's. If you need it elsewhere, pass the dispatcher explicitly; do not assume it defaults to
Default.
Best Practices
- Send CPU-bound computation to
Dispatchers.Defaultand blocking waits toDispatchers.IO, matching each task to the department built for it.
- Keep
Dispatchers.Mainfree; push any non-trivial work off it withwithContextso the interface stays responsive.
- Use
withContextto switch dispatchers for a scoped block, and remember it restores the previous context when the block ends.
- Treat
CoroutineContextas a set of elements combined with+; look elements up by key and change only the ones you intend to.
- Reach for
launchorasyncwhen you want concurrency, andwithContextwhen you only want to move where a block runs.
- Give coroutines a
CoroutineNamein code you will need to debug, since the name is stable while thread identities are not.
- Avoid
Dispatchers.Unconfinedin application code; its resume-anywhere behaviour is for advanced, deliberate uses only.
- Close any custom dispatcher you create from an executor, and prefer the standard dispatchers to avoid leaking threads.
Practice Exercises
- Write a
runBlockingmainthat computes the product of 1 through 6 insidewithContext(Dispatchers.Default), printing a line before and after. Predict the exact order of the three lines and the product value.
- Launch a coroutine with a context that combines
CoroutineName("calc")andDispatchers.Defaultusing+, and read both the name back fromcoroutineContextinside it. Confirm the name prints deterministically.
- Nest two
withContext(CoroutineName(...))blocks and read the name before, inside each level, and after. Trace on paper how the name changes and reverts, then confirm against the output.
- Take the
summarizepipeline from this lesson and split it so the blocking read stays onDispatchers.IOwhile the aggregation runs in a separatewithContext(Dispatchers.Default). Add a comment explaining why each phase belongs on its dispatcher.