Dispatchers and threading

You will understand how to manage thread switching, ensure main-safety, and correctly use different dispatchers to prevent UI freezes and resource leaks. About 25 minutes.

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.Main is the waiter taking orders and serving customers.
  • Dispatchers.IO is the delivery driver bringing ingredients from outside.
  • Dispatchers.Default is 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.

DispatcherThreadsTypical task
Dispatchers.MainThe Android main threadUpdating UI state, calling Android UI APIs
Dispatchers.Main.immediateThe main thread, without re-posting if you are already on itThe default for viewModelScope and lifecycleScope
Dispatchers.DefaultA pool with one thread per CPU core, at least 2CPU work: sorting large lists, parsing big JSON, image processing
Dispatchers.IORuns up to 64 tasks at once by default (or the core count, if higher), on threads shared with DefaultBlocking calls: file access, blocking SDKs, JDBC, Thread.sleep-style APIs

Two details often come up:

  • Dispatchers.IO and Dispatchers.Default share 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.

Switching threads with withContext
Switching threads with withContext A coroutine started with viewModelScope.launch runs on Main.immediate. It calls withContext(Dispatchers.IO), which suspends it while a blocking call such as a file read runs on an IO thread. Meanwhile the main thread stays free. When the work ends, the coroutine resumes on Main with the result and updates the UI state. Starts on Main.immediate Free to draw and handle taps Resumes on Main viewModelScope.launch withContext(IO) BLOCKING FILE CALL RESULT UPDATE UI STATE Main thread UI work Coroutine viewModelScope Dispatchers.IO thread pool
The Main thread never waits: withContext suspends the coroutine, runs the blocking call on IO, then resumes on Main with the result.

Notes

  • Make suspend functions main-safe: put withContext around the blocking or heavy part, in the class that does that work.
  • Use Dispatchers.IO for calls that block a thread while waiting: files, blocking SDKs, legacy synchronous APIs.
  • Use Dispatchers.Default for CPU work. Its size matches the core count, so CPU tasks do not fight over far more threads than there are cores.
  • withContext suspends 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.
  • delay suspends without blocking a thread. Thread.sleep blocks the thread and does not react to cancellation.
  • dispatcher.limitedParallelism(n) returns a view that runs at most n coroutines 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.IO made with limitedParallelism are not limited by IO's 64, so a separate pool for a slow SDK will not use up the shared IO slots.
  • Dispatchers.Main needs an Android main looper (from kotlinx-coroutines-android). In local unit tests, replace it with Dispatchers.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 withContext returns its block's value to the caller's dispatcher.
  • In a test, pass StandardTestDispatcher(testScheduler) for both parameters so the work runs on the runTest scheduler.

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

The Frozen Checkout Screen
  • Play Console showed ANRs on the checkout screen, mostly on low-end devices.
  • viewModelScope.launch parsed a large receipt JSON right after a suspend Retrofit call. The Retrofit call was main-safe, but the parsing ran on Dispatchers.Main.immediate.
  • The main thread was blocked for seconds, so input events were not handled.
The fix
  • Moved the parsing into OrderRepository inside withContext(defaultDispatcher), injected as Dispatchers.Default.
  • Turned on StrictMode and watched frame timings in debug builds to catch similar work on the main thread.
  • The ANR cluster disappeared in the next release.
Flaky repository tests
  • Repository tests passed locally but failed now and then on CI.
  • The repository called withContext(Dispatchers.IO) directly, so inside runTest the work ran on a real background thread.
  • Some assertions ran before that work finished, and runTest could not skip the delay calls inside it, so the tests were also slow.
The fix
  • Changed the repository to take ioDispatcher: CoroutineDispatcher in its constructor, defaulting to Dispatchers.IO.
  • Tests pass StandardTestDispatcher(testScheduler), so the work runs on the runTest scheduler with virtual time.
  • ViewModel tests also replace Dispatchers.Main with Dispatchers.setMain in a JUnit rule, because viewModelScope uses it.

Common mistakes

  • Hardcoding Dispatchers.IO in classes. Tests then run that work on real threads, outside the runTest scheduler, which makes them slow and flaky. Inject the dispatcher.
  • Assuming suspend means background. A suspend fun that calls a blocking API still blocks the thread it runs on. Wrap the blocking call in withContext.
  • 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 Mutex for 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.

  1. Create a data class DataResult(val content: String).
  2. Create an interface DataRepository with a suspend function getData(): DataResult.
  3. Implement DataRepository in a class called NetworkDataRepository.
  4. The implementation must take a CoroutineDispatcher as a constructor parameter.
  5. Inside getData(), use withContext to switch to the provided dispatcher.
  6. Inside the withContext block, call Thread.sleep(2000) to simulate a slow blocking call, print Thread.currentThread().name, and return DataResult("Success").
  7. In main, use runBlocking. Start a second coroutine with launch that prints "main thread is free" after delay(100), then call NetworkDataRepository(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().

Next: Structured concurrency and cancellation