Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 14 / Topic 5 of 7

Dispatchers

A dispatcher decides which thread (or thread pool) a coroutine actually runs on. Dispatchers.Default is sized for CPU-bound work (roughly one thread per core); Dispatchers.IO is a larger pool meant for calls that genuinely block a thread (a blocking database driver, Thread.sleep, legacy blocking I/O). withContext switches the current coroutine to a different dispatcher for one block, then switches back.

suspend fun blockingDbCall(id: String): String =
    withContext(Dispatchers.IO) {   // moves this block to a thread pool meant for blocking calls
        Thread.sleep(50)            // pretend JDBC/file-system call -- this genuinely blocks a thread
        "$id row fetched"
    }
withContext(Dispatchers.Default) {
    println("sum = ${cpuHeavyCheck(1_000_000)}")
}

val results = listOf("C-01", "C-02", "C-03").map { id ->
    async { blockingDbCall(id) }
}.awaitAll()
results.forEach { println(it) }

val seenThreads = mutableSetOf<String>()
val jobs = List(1000) {
    launch(Dispatchers.Default) {
        delay(10)
        seenThreads.add(Thread.currentThread().name)
    }
}
jobs.joinAll()
println("1000 coroutines ran across ${seenThreads.size} thread(s) (varies, always far fewer than 1000)")
main runs on a coroutine, backed by some thread (name varies)
sum = 500000500000
C-01 row fetched
C-02 row fetched
C-03 row fetched
1000 coroutines ran across 18 thread(s) (varies, always far fewer than 1000)

1,000 coroutines ran across 18 real threads on this machine (the exact number varies run to run and machine to machine, but it is always a small pool, never anywhere close to 1,000) -- a coroutine is a cheap, suspendable unit of work scheduled onto a thread, not a thread of its own. That's the whole reason coroutines scale where one-thread-per-task designs don't.

Full program: examples/05_dispatchers.kt.

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide