Careeroza
Dispatchers Overview
Which Thread?
A dispatcher decides which thread or thread pool runs a coroutine.
| Dispatcher | Threads | Use for |
|---|---|---|
Dispatchers.Main | Android UI thread (needs kotlinx-coroutines-android) | updating UI, calling suspend functions that are main-safe |
Dispatchers.Default | shared pool, size = number of CPU cores (min 2) | CPU work: sorting, JSON parsing, image filters |
Dispatchers.IO | shares threads with Default, up to 64 (or more) at once | blocking I/O: files, JDBC, old blocking SDKs |
Dispatchers.Unconfined | whatever thread resumes it | rare; tests and special cases |
See the Threads
Example
Print the thread each coroutine starts on. Worker numbers change between runs, so only the pool name is printed.
import kotlinx.coroutines.*
fun threadName() = Thread.currentThread().name.substringBefore("-worker")
fun main() = runBlocking {
launch { println("runBlocking: ${threadName()}") }.join()
launch(Dispatchers.Default) { println("Default: ${threadName()}") }.join()
launch(Dispatchers.IO) { println("IO: ${threadName()}") }.join()
launch(Dispatchers.Unconfined) {
println("Unconfined before delay: ${threadName()}")
delay(50)
println("Unconfined after delay: ${threadName()}")
}.join()
}Output
runBlocking: main Default: DefaultDispatcher IO: DefaultDispatcher Unconfined before delay: main Unconfined after delay: kotlinx.coroutines.DefaultExecutor
Note: Dispatchers.Default and Dispatchers.IO share the same threads named DefaultDispatcher-worker-N. Switching between them often costs no thread switch at all.