Dispatchers and threading
Why it matters
- Blocking the main thread causes jank, and long blocks cause Application Not Responding (ANR) errors.
- Running shared mutable state on a multi-threaded dispatcher without protection causes race conditions.
- Interviewers test whether you can tell CPU-bound work from blocking I/O, and know why the two dispatchers differ.
- Code that is 'main-safe' can be called from any thread, which keeps ViewModels simple.
The simple explanation
- A restaurant kitchen.
Dispatchers.Mainis the waiter taking orders and serving customers.Dispatchers.IOis the delivery driver bringing ingredients from outside.Dispatchers.Defaultis the chef chopping vegetables and cooking.- If the waiter starts cooking, no one gets served (UI freeze).
- If the chefs spend their time waiting at the door for deliveries, nobody is cooking (CPU threads stuck on blocking I/O).
In Kotlin coroutines, a CoroutineDispatcher decides which thread or thread pool a coroutine runs on. launch and async do not pick a background thread for you: without an explicit dispatcher they use the one from the scope they are started in. viewModelScope and lifecycleScope use Dispatchers.Main.immediate.
The goal is main-safety: a suspend function should be safe to call from the main thread, because it moves its own blocking or heavy work elsewhere with withContext.
| Dispatcher | Threads | Typical task |
|---|---|---|
Dispatchers.Main | The Android main thread | Updating UI state, calling Android UI APIs |
Dispatchers.Main.immediate | The main thread, without re-posting if you are already on it | The default for viewModelScope and lifecycleScope |
Dispatchers.Default | A pool with one thread per CPU core, at least 2 | CPU work: sorting large lists, parsing big JSON, image processing |
Dispatchers.IO | Runs up to 64 tasks at once by default (or the core count, if higher), on threads shared with Default | Blocking calls: file access, blocking SDKs, JDBC, Thread.sleep-style APIs |
Two details often come up:
Dispatchers.IOandDispatchers.Defaultshare one thread pool. Switching from Default to IO often keeps running on the same thread; only the limits differ.- Suspend APIs from Room, Retrofit and Ktor are already main-safe. You do not need to wrap them in
withContext(Dispatchers.IO).
For tests, inject the dispatcher through the constructor (for example as an ioDispatcher: CoroutineDispatcher = Dispatchers.IO parameter). A test can then pass a TestDispatcher that shares the runTest scheduler, so delays are skipped and the order of work is predictable.
Notes
- Make suspend functions main-safe: put
withContextaround the blocking or heavy part, in the class that does that work. - Use
Dispatchers.IOfor calls that block a thread while waiting: files, blocking SDKs, legacy synchronous APIs. - Use
Dispatchers.Defaultfor CPU work. Its size matches the core count, so CPU tasks do not fight over far more threads than there are cores. withContextsuspends the caller, runs the block on the given dispatcher, and resumes the caller on its own dispatcher with the result. It does not start a separate coroutine you have to manage.delaysuspends without blocking a thread.Thread.sleepblocks the thread and does not react to cancellation.dispatcher.limitedParallelism(n)returns a view that runs at mostncoroutines at the same time on the original pool. It caps parallelism, not threads, and a suspended coroutine does not hold a slot.- Views of
Dispatchers.IOmade withlimitedParallelismare not limited by IO's 64, so a separate pool for a slow SDK will not use up the shared IO slots. Dispatchers.Mainneeds an Android main looper (fromkotlinx-coroutines-android). In local unit tests, replace it withDispatchers.setMain(testDispatcher).- Inject dispatchers into classes so tests can control them.
Code example
A repository that reads a file (blocking I/O) and parses it (CPU work), with both dispatchers injected so tests can replace them.
import java.io.File
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
data class Report(val lines: List<String>)
class ReportRepository(
private val cacheDir: File,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default,
) {
// Main-safe: a ViewModel can call this from viewModelScope directly
suspend fun loadReport(name: String): Report {
val raw = withContext(ioDispatcher) {
File(cacheDir, name).readText() // blocking file read
}
return withContext(defaultDispatcher) {
Report(raw.lines().filter { it.isNotBlank() }.sorted()) // CPU work
}
}
}- The repository owns its main-safety: callers never need to know which thread it uses.
- Each
withContextreturns its block's value to the caller's dispatcher. - In a test, pass
StandardTestDispatcher(testScheduler)for both parameters so the work runs on therunTestscheduler.
Run the idea in plain Kotlin
Watch the thread change inside withContext and come back afterwards. Dispatchers.IO and Dispatchers.Default print the same pool name because they share threads.
import kotlinx.coroutines.*
fun where(): String {
val name = Thread.currentThread().name
return if (name.startsWith("DefaultDispatcher-worker")) "shared worker pool" else name
}
suspend fun parse(text: String): Int = withContext(Dispatchers.Default) {
println("parse runs on: " + where())
text.split(" ").size
}
suspend fun read(): String = withContext(Dispatchers.IO) {
println("read runs on: " + where())
"one two three four"
}
fun main() = runBlocking {
println("caller runs on: " + where())
val words = parse(read())
println("back on: " + where() + ", words = " + words)
}Expected output:
caller runs on: main
read runs on: shared worker pool
parse runs on: shared worker pool
back on: main, words = 4
In production
- Play Console showed ANRs on the checkout screen, mostly on low-end devices.
viewModelScope.launchparsed a large receipt JSON right after a suspend Retrofit call. The Retrofit call was main-safe, but the parsing ran onDispatchers.Main.immediate.- The main thread was blocked for seconds, so input events were not handled.
- Moved the parsing into
OrderRepositoryinsidewithContext(defaultDispatcher), injected asDispatchers.Default. - Turned on
StrictModeand watched frame timings in debug builds to catch similar work on the main thread. - The ANR cluster disappeared in the next release.
- Repository tests passed locally but failed now and then on CI.
- The repository called
withContext(Dispatchers.IO)directly, so insiderunTestthe work ran on a real background thread. - Some assertions ran before that work finished, and
runTestcould not skip thedelaycalls inside it, so the tests were also slow.
- Changed the repository to take
ioDispatcher: CoroutineDispatcherin its constructor, defaulting toDispatchers.IO. - Tests pass
StandardTestDispatcher(testScheduler), so the work runs on therunTestscheduler with virtual time. - ViewModel tests also replace
Dispatchers.MainwithDispatchers.setMainin a JUnit rule, becauseviewModelScopeuses it.
Common mistakes
- Hardcoding Dispatchers.IO in classes. Tests then run that work on real threads, outside the
runTestscheduler, which makes them slow and flaky. Inject the dispatcher. - Assuming suspend means background. A
suspend funthat calls a blocking API still blocks the thread it runs on. Wrap the blocking call inwithContext. - Using Dispatchers.IO for heavy CPU work. IO allows up to 64 tasks at once, far more than there are cores, so CPU tasks compete with each other and take slots from real I/O. Use Default.
- Wrapping already main-safe calls. Room and Retrofit suspend functions switch threads themselves. Adding
withContext(Dispatchers.IO)around them is harmless but adds noise. - Using limitedParallelism(1) as a lock. It runs one coroutine at a time only between suspension points. Once a coroutine suspends, another one can start, so a read-suspend-write sequence is still not atomic. Use a
Mutexfor that. - Calling runBlocking on the main thread. It blocks the main thread until the work finishes, which is exactly the ANR you were trying to avoid.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between Dispatchers.IO and Dispatchers.Default?”
“How do you make a suspend function main-safe?”
“What happens if you call a blocking function like Thread.sleep() inside a coroutine on Dispatchers.Main?”
“Why should you inject Dispatchers instead of using the static Dispatchers object?”
Quiz
Which dispatcher is best suited for parsing a 50MB JSON string?
What is the primary purpose of withContext?
A coroutine on Dispatchers.Main calls a function that uses withContext(Dispatchers.IO). What does the main thread do meanwhile?
Which of these does NOT make a suspend function main-safe?
0 of 4 answered
Mini task
Task: Implement a Main-Safe Repository
Goal: Create a repository that fetches data from a simulated network and ensures it is safe to call from the UI.
- Create a data class
DataResult(val content: String). - Create an interface
DataRepositorywith a suspend functiongetData(): DataResult. - Implement
DataRepositoryin a class calledNetworkDataRepository. - The implementation must take a
CoroutineDispatcheras a constructor parameter. - Inside
getData(), usewithContextto switch to the provided dispatcher. - Inside the
withContextblock, callThread.sleep(2000)to simulate a slow blocking call, printThread.currentThread().name, and returnDataResult("Success"). - In
main, userunBlocking. Start a second coroutine withlaunchthat prints "main thread is free" afterdelay(100), then callNetworkDataRepository(Dispatchers.IO).getData()and print the result.
Done Condition: "main thread is free" prints before the result, the sleep prints a DefaultDispatcher-worker thread name, and passing a different dispatcher to the constructor changes where the sleep runs without touching getData().