Dispatchers and CoroutineContext

Dispatchers and CoroutineContext in Kotlin: --- A large hospital routes every incoming task to the department staffed for it, and three departments make the…


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.

DispatcherBacking threadsSend it
Defaultpool sized to CPU coresCPU-bound computation
IOlarge elastic poolblocking I/O and waits
Mainthe single UI threadcode that touches UI state
Unconfinedno threads of its ownadvanced 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.

ElementWhat it carries
Joblifecycle and cancellation
CoroutineDispatcherwhich thread or pool runs the code
CoroutineNamea debug label for the coroutine
CoroutineExceptionHandlerhandling 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

  1. Running CPU-bound work on Dispatchers.IO. The IO pool is for waiting tasks. Heavy loops and computation belong on Dispatchers.Default, which is sized to the cores. Leaving compute on IO can exhaust the pool meant for real blocking calls.
  1. 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 on IO, which has slack for threads that mostly sit idle.
  1. Blocking the Main dispatcher. Long work on the UI thread freezes the interface. Move it off with withContext(Dispatchers.Default) and let Main stay free to serve the interface.
  1. Treating withContext as if it starts a new coroutine. withContext suspends the current coroutine and switches context; it does not add concurrency. For concurrent work you still need launch or async.
  1. 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.
  1. Printing or asserting on thread names. Which pool thread runs a block varies between runs. Depending on Thread.currentThread().name gives flaky behaviour and non-reproducible output; depend on computed values instead.
  1. Overriding the Job when combining context. Passing a fresh Job into 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.
  1. Leaking custom dispatchers. A dispatcher built from an executor or newFixedThreadPoolContext holds real threads that must be closed. Prefer the standard dispatchers, and if you must build one, close it when done.
  1. 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.Default and blocking waits to Dispatchers.IO, matching each task to the department built for it.
  • Keep Dispatchers.Main free; push any non-trivial work off it with withContext so the interface stays responsive.
  • Use withContext to switch dispatchers for a scoped block, and remember it restores the previous context when the block ends.
  • Treat CoroutineContext as a set of elements combined with +; look elements up by key and change only the ones you intend to.
  • Reach for launch or async when you want concurrency, and withContext when you only want to move where a block runs.
  • Give coroutines a CoroutineName in code you will need to debug, since the name is stable while thread identities are not.
  • Avoid Dispatchers.Unconfined in 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

  1. Write a runBlocking main that computes the product of 1 through 6 inside withContext(Dispatchers.Default), printing a line before and after. Predict the exact order of the three lines and the product value.
  1. Launch a coroutine with a context that combines CoroutineName("calc") and Dispatchers.Default using +, and read both the name back from coroutineContext inside it. Confirm the name prints deterministically.
  1. 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.
  1. Take the summarize pipeline from this lesson and split it so the blocking read stays on Dispatchers.IO while the aggregation runs in a separate withContext(Dispatchers.Default). Add a comment explaining why each phase belongs on its dispatcher.