Dispatchers & Threading Interview Questions

KOTLIN › Coroutines

What are the main coroutine dispatchers, and what is each one for?

What a strong answer covers: Dispatchers.Main runs on the Android main thread for UI work. Dispatchers.IO is for blocking I/O like disk, database and network calls, with a large pool (64 threads or the core count, whichever is higher). Dispatchers.Default is for CPU-heavy work like parsing, sorting or image processing, sized to the number of cores. Dispatchers.Unconfined runs in whatever thread resumed it and is rarely used in app code.

What does withContext do, and what does it mean for a function to be main-safe?

What a strong answer covers: withContext switches the coroutine to another dispatcher for a block and returns its result, then resumes on the original dispatcher. A main-safe function can be called from the main thread without blocking it, because it moves its own blocking work off Main inside. Repositories and data sources should be main-safe so callers don't need to know about threading.

Dispatchers.IO and Dispatchers.Default share threads. How does that work, and why does it matter which one you choose?

What a strong answer covers: They share one underlying thread pool, so switching between them often avoids a real thread switch. But they have separate limits: Default is capped at the core count so CPU work doesn't oversubscribe the CPU, while IO allows many more threads because blocked threads aren't using CPU. Putting blocking calls on Default can starve CPU work; putting heavy CPU work on IO creates too many competing threads.

What is Dispatchers.Main.immediate, and when does it make a difference?

What a strong answer covers: Main.immediate runs the coroutine straight away without re-posting to the Looper if you're already on the main thread, while Main always dispatches through the message queue. viewModelScope and lifecycleScope use it, so updates happen in the same frame and you avoid a one-frame delay or flicker when you're already on Main.

How would you limit a coroutine-heavy feature to at most 4 concurrent database writes, and why is a custom fixed thread pool often the wrong answer?

What a strong answer covers: Use Dispatchers.IO.limitedParallelism(4), which creates a view of the IO pool capped at 4 without new threads, or a Semaphore(4) with withPermit if you need to limit concurrent operations rather than threads. A newFixedThreadPoolContext needs explicit closing, leaks threads if you forget, and doesn't share threads with the rest of the app. limitedParallelism(1) is also a cheap way to serialise access to non-thread-safe state.

Back to Dispatchers & Threading