Dispatchers Overview

Which Thread?

A dispatcher decides which thread or thread pool runs a coroutine.

DispatcherThreadsUse for
Dispatchers.MainAndroid UI thread (needs kotlinx-coroutines-android)updating UI, calling suspend functions that are main-safe
Dispatchers.Defaultshared pool, size = number of CPU cores (min 2)CPU work: sorting, JSON parsing, image filters
Dispatchers.IOshares threads with Default, up to 64 (or more) at onceblocking I/O: files, JDBC, old blocking SDKs
Dispatchers.Unconfinedwhatever thread resumes itrare; 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.