← Back to writing

How Coroutine Dispatchers Actually Work

Dispatchers.IO is not a pool of IO threads. What the CoroutineScheduler really does, and the mental model that replaced mine.

  • Kotlin
  • Coroutines
  • Android
  • Concurrency
On this page
  1. One scheduler, two sets of rules
  2. The switch that doesn’t switch threads
  3. What follows for Android code
  4. Further reading

Claim Dispatchers.Default and Dispatchers.IO are two policies applied to one CoroutineScheduler, not two thread pools.

Evidence The worker lifecycle in CoroutineScheduler.kt: CPU permits equal to corePoolSize (the core count, minimum 2), blocking tasks allowed up to maxPoolSize (64 or the core count) without a permit, one work-stealing queue of 128 per worker.

The catch A switch from Default to IO often keeps the same worker thread; it releases a CPU permit and relabels itself. The shared ceiling also means 64 blocking tasks that never return can starve Default.

In practice Put timeouts on blocking calls, and use limitedParallelism(n) for a bounded view of the same pool instead of a new executor.

Dispatchers.IO is not a pool of I/O threads, and Dispatchers.Default is not a pool of CPU threads. They are two sets of rules applied to one scheduler, and a switch between them often does not move your code to another thread at all. That is the claim. The rest of this piece is kotlinx.coroutines earning it.

Most Android documentation explains coroutine dispatchers like this:

Use Dispatchers.Default for CPU-intensive operations like sorting lists or parsing JSON. Use Dispatchers.IO for blocking I/O like reading files or database queries.

From that rule of thumb, it is easy to assume that Kotlin keeps two separate thread pools under the hood: one small pool sized to your CPU cores, and one large pool reserved for I/O. The explanation is convenient, and for years I assumed the architecture looked exactly like this:

[Dispatchers.Default] ──► ThreadPool A (Threads = CPU Cores)
[Dispatchers.IO]      ──► ThreadPool B (Threads = up to 64)

In that model, switching from Dispatchers.Default to Dispatchers.IO means handing a task to an entirely different thread pool and paying for it: a thread context switch, cache invalidation, queue synchronization. It also means thread exhaustion in Dispatchers.IO is completely isolated from Dispatchers.Default. Neither assumption is true, and the actual implementation is more elegant than the folklore.

One scheduler, two sets of rules

Both Dispatchers.Default and Dispatchers.IO share the exact same instance of an internal class called CoroutineScheduler:

Dispatchers.Default ─┐
                     ├─► CoroutineScheduler ──► Pool of Worker Threads
Dispatchers.IO ──────┘                           (Parked / CPU / Blocking)

The difference between Default and IO is not which threads they own. It is the rules under which their tasks are permitted to run. The scheduler keeps a finite number of CPU permits, equal to corePoolSize, which is typically the number of CPU cores on the device, with a minimum of 2. A non-blocking task, which is what Dispatchers.Default dispatches, must acquire one of these permits before it runs. A worker holding a CPU permit is guaranteed that no more than corePoolSize threads are executing CPU-bound calculations at once, which avoids excessive OS time-slicing. A blocking task, from Dispatchers.IO, does not consume a CPU permit. Blocking tasks run up to a higher ceiling, maxPoolSize, which defaults to 64 or the core count, and when a worker enters a blocking state it yields its CPU permit back to the scheduler, so another worker can wake up and run Default tasks.

Interactive demo: launch tasks on Dispatchers.Default and Dispatchers.IO and watch them share one pool of workers. Needs JavaScript.

The source makes the policy concrete. If you inspect kotlinx.coroutines.scheduling.CoroutineScheduler.kt, you find the core worker lifecycle:

internal enum class WorkerState {
    CPU_ACQUIRED, // Actively executing a CPU-bound task (Default)
    BLOCKING,     // Executing a blocking task (IO)
    PARKED,       // Sleeping waiting for work
    DORMANT,
    TERMINATED
}

When you dispatch a task via Dispatchers.Default, the scheduler tags the runnable as TASK_NON_BLOCKING. When dispatched via Dispatchers.IO, it is tagged as TASK_PROBABLY_BLOCKING. Here is what happens inside a worker thread when it picks up a task:

// Simplified from CoroutineScheduler.Worker.runWorker()
fun runWorker() {
    while (!isTerminated) {
        val task = findTask()
        if (task != null) {
            executeTask(task)
        } else {
            park()
        }
    }
}

private fun executeTask(task: Task) {
    val taskMode = task.mode
    if (taskMode == TASK_NON_BLOCKING) {
        // Must acquire CPU permit
        if (state != WorkerState.CPU_ACQUIRED) {
            tryAcquireCpuPermit()
        }
    } else {
        // Blocking task: release CPU permit so another thread can do CPU work!
        if (state == WorkerState.CPU_ACQUIRED) {
            releaseCpuPermit()
            state = WorkerState.BLOCKING
        }
    }
    task.run()
}

The switch that doesn’t switch threads

Because both dispatchers share the same thread pool and worker queue, look at what happens with this standard Android pattern:

suspend fun loadUserData(): UserData = withContext(Dispatchers.Default) {
    val processedId = computeHash(userId) // CPU bound
    
    val data = withContext(Dispatchers.IO) {
        database.load(processedId)        // Blocking IO
    }
    
    transformPayload(data)                // Back on Default
}

What thread runs database.load()? In many cases, the exact same worker thread. When execution reaches withContext(Dispatchers.IO), the worker calls releaseCpuPermit() and moves its internal state from CPU_ACQUIRED to BLOCKING. It signals the scheduler that it is about to block on I/O, so if there is pending CPU work a parked thread should wake up. Then it carries on running your database query on the same hardware thread. There is no thread hop, no IPC, and no OS context switch. When the query completes and execution returns to Dispatchers.Default, the worker re-acquires a CPU permit, parking only if all CPU permits are currently claimed by active threads.

The queueing is what makes staying put the likely outcome. The CoroutineScheduler uses a classic work-stealing algorithm inspired by Java’s ForkJoinPool and Go’s scheduler. Each worker thread owns a lock-free, single-producer circular array queue of capacity 128, the WorkQueue. When a coroutine resumes, it is pushed directly to the current thread’s local queue, which keeps it close to the cache. A worker that drains its own queue tries to steal tasks from sibling workers before falling back to the global shared queue, and only if all queues are empty does the thread park via LockSupport.parkNanos().

What follows for Android code

The shared pool cuts both ways. Because both dispatchers share a thread pool ceiling (maxPoolSize), if rogue code spawns 64 blocking tasks that block indefinitely without using suspending APIs, you can saturate the scheduler’s ability to create new workers, and Dispatchers.IO starvation reaches Dispatchers.Default. Always use proper timeouts on blocking calls.

The same design is what makes limitedParallelism cheap. In modern kotlinx.coroutines, Dispatchers.IO.limitedParallelism(n) creates a view that restricts concurrent execution to n tasks without allocating a new thread pool:

// Limits disk writes to 2 concurrent operations without creating a new Executor:
val diskDispatcher = Dispatchers.IO.limitedParallelism(2)

Tasks dispatched to diskDispatcher are queued internally and fed into the shared CoroutineScheduler only when permits are free.

So the model that replaced mine has three parts. Default and IO are policies, not pools; they share a single pool of workers managed by CoroutineScheduler. Context switching between them can be free, because it often re-labels the current worker thread rather than bouncing to another one. And CPU permits are what prevent thrashing, letting the scheduler balance CPU-intensive algorithms and blocking I/O on the same hardware.

Further reading

  • kotlinx.coroutines source repository: kotlinx/coroutines/scheduling/CoroutineScheduler.kt
  • Roman Elizarov: Blocking threads, suspending coroutines

How useful was this article?

Only the author sees ratings.