Dispatchers and threads

suggest change

A coroutine is not a thread. It is a piece of work that can be suspended and resumed, and something has to decide which thread it runs on each time it resumes. In kotlinx.coroutines that something is a dispatcher.

Picking the right dispatcher is how you keep a UI responsive, avoid starving the CPU pool with blocking I/O, and limit how many database connections are used at once. This article covers:

The examples use this dependency (see Coroutines for the basics of launch, async and runBlocking):

// build.gradle.kts
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}

Where does a coroutine run?

Every coroutine has a CoroutineContext, and one element of that context is its dispatcher. You pass a dispatcher to launch, async or withContext; if you don't, the coroutine inherits the dispatcher of its parent scope.

The easiest way to learn how dispatchers behave is to print the current thread:

import kotlinx.coroutines.*
import java.util.concurrent.Executors

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

fun main() = runBlocking<Unit> {
    log("runBlocking")
    launch { log("launch, inherits context") }.join()
    launch(Dispatchers.Default) { log("Dispatchers.Default") }.join()
    launch(Dispatchers.IO) { log("Dispatchers.IO") }.join()
    launch(Dispatchers.Unconfined) { log("Dispatchers.Unconfined") }.join()
    Executors.newSingleThreadExecutor { r -> Thread(r, "my-thread") }
        .asCoroutineDispatcher()
        .use { myDispatcher ->
            launch(myDispatcher) { log("custom dispatcher") }.join()
        }
}
[main] runBlocking
[main] launch, inherits context
[DefaultDispatcher-worker-1] Dispatchers.Default
[DefaultDispatcher-worker-1] Dispatchers.IO
[main] Dispatchers.Unconfined
[my-thread] custom dispatcher

Some things to notice:

A tip about fun main() = runBlocking<Unit> { ... }: the explicit <Unit> makes sure main returns Unit even when the block's last expression is, for example, a launch call that returns a Job. Without it, main would return Job, and the JVM would fail with "Main method not found".

Debug mode

Run the JVM with -Dkotlinx.coroutines.debug (or -ea, which turns it on too) and the library appends the coroutine name and id to the thread name:

[main @coroutine#1] runBlocking
[main @coroutine#2] launch, inherits context
[DefaultDispatcher-worker-1 @coroutine#3] Dispatchers.Default
[DefaultDispatcher-worker-1 @coroutine#4] Dispatchers.IO
[main @coroutine#5] Dispatchers.Unconfined
[my-thread @coroutine#6] custom dispatcher

This is the same output as before, but now you can tell which coroutine printed each line. Give coroutines meaningful names with CoroutineName, which is also a context element. The dispatcher itself can be read from the context with the ContinuationInterceptor key:

import kotlinx.coroutines.*
import kotlin.coroutines.ContinuationInterceptor

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

fun main() = runBlocking(CoroutineName("main")) {
    log("dispatcher = ${coroutineContext[ContinuationInterceptor]}")
    launch(Dispatchers.Default + CoroutineName("fetcher")) {
        log("dispatcher = ${coroutineContext[ContinuationInterceptor]}")
        withContext(Dispatchers.IO) {
            log("dispatcher = ${coroutineContext[ContinuationInterceptor]}")
        }
    }.join()
    val single = Dispatchers.Default.limitedParallelism(1, "single")
    withContext(single) {
        log("dispatcher = ${coroutineContext[ContinuationInterceptor]}")
    }
}

Run with -Dkotlinx.coroutines.debug:

[main @main#1] dispatcher = BlockingEventLoop@7dc5e7b4
[DefaultDispatcher-worker-1 @fetcher#2] dispatcher = Dispatchers.Default
[DefaultDispatcher-worker-1 @fetcher#2] dispatcher = Dispatchers.IO
[DefaultDispatcher-worker-1 @main#1] dispatcher = single

Context elements are combined with +. A later element of the same kind replaces an earlier one, so Dispatchers.Default + CoroutineName("fetcher") keeps the parent's job but replaces its dispatcher and name.

The built-in dispatchers

Dispatcher Threads Use for
Dispatchers.Default as many as CPU cores (at least 2) CPU-bound work: parsing, sorting, image processing, crypto
Dispatchers.IO up to 64 (or the number of cores, if larger), shared with Default blocking I/O: JDBC, java.io files, blocking HTTP clients
Dispatchers.Main the single UI thread touching UI state on Android, Swing, JavaFX
Dispatchers.Unconfined whatever thread resumed it rare special cases and tests

launch and async called on GlobalScope or a scope without a dispatcher use Dispatchers.Default.

Dispatchers.Default: CPU-bound work

Default has one thread per CPU core, which is exactly the right number for work that keeps the CPU busy: more threads would just compete for the same cores.

Splitting a CPU-heavy job into chunks and running them with async on Default uses all cores:

import kotlinx.coroutines.*
import kotlin.time.measureTime

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    var i = 2
    while (i * i <= n) {
        if (n % i == 0) return false
        i++
    }
    return true
}

fun countPrimes(range: IntRange): Int = range.count(::isPrime)

fun main() = runBlocking {
    val limit = 20_000_000
    val chunks = Runtime.getRuntime().availableProcessors()

    var sequential = 0
    val t1 = measureTime { sequential = countPrimes(1..limit) }
    println("sequential: $sequential primes in ${t1.inWholeMilliseconds} ms")

    var parallel = 0
    val t2 = measureTime {
        parallel = withContext(Dispatchers.Default) {
            val size = limit / chunks
            (0 until chunks).map { c ->
                val from = c * size + 1
                val to = if (c == chunks - 1) limit else from + size - 1
                async { countPrimes(from..to) }
            }.awaitAll().sum()
        }
    }
    println("parallel:   $parallel primes in ${t2.inWholeMilliseconds} ms ($chunks chunks)")
}

Output on a machine with 24 logical CPUs:

sequential: 1270607 primes in 7687 ms
parallel:   1270607 primes in 914 ms (24 chunks)

The async calls inside withContext(Dispatchers.Default) inherit Default from the enclosing scope, so there's no need to repeat it on every async.

Dispatchers.IO: blocking calls

Many Java APIs block the calling thread: JDBC, File.readText(), Thread.sleep, InputStream.read, older HTTP clients. A blocked thread does nothing useful, but it still occupies a slot in its pool.

If you run blocking calls on Default, you quickly use up all its threads and everything else waits. Dispatchers.IO allows many more threads at once (64 by default) precisely so that blocked threads don't starve the system:

import kotlinx.coroutines.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.time.measureTime

suspend fun blockingTasks(dispatcher: CoroutineDispatcher, count: Int): Int {
    val threads = ConcurrentHashMap.newKeySet<String>()
    coroutineScope {
        repeat(count) {
            launch(dispatcher) {
                threads += Thread.currentThread().name
                Thread.sleep(1000) // blocking call, e.g. JDBC or file I/O
            }
        }
    }
    return threads.size
}

fun main() = runBlocking {
    println("CPU cores: ${Runtime.getRuntime().availableProcessors()}")
    for ((name, d) in listOf("Default" to Dispatchers.Default, "IO" to Dispatchers.IO)) {
        var used = 0
        val t = measureTime { used = blockingTasks(d, 100) }
        println("$name: 100 blocking tasks took ${t.inWholeMilliseconds / 100 * 100} ms using $used threads")
    }
}
CPU cores: 24
Default: 100 blocking tasks took 5000 ms using 24 threads
IO: 100 blocking tasks took 2000 ms using 64 threads

With 24 threads, 100 one-second tasks need 5 rounds. With 64 threads they need 2. While the Default run was going on, any CPU work submitted to Default by other parts of the program would have had to wait too.

You can raise the limit with the system property kotlinx.coroutines.io.parallelism, but a better tool is limitedParallelism, shown below.

Calling suspend functions like delay, Ktor client calls or Flow.collect doesn't need Dispatchers.IO: they suspend instead of blocking, and free the thread while waiting. IO is only for code that actually blocks.

Blocking a single-threaded dispatcher

Blocking is even worse on a dispatcher with only one thread, like runBlocking's event loop or Dispatchers.Main. Compare blocking, suspending, and offloading to IO:

import kotlinx.coroutines.*
import kotlin.time.measureTime

fun main() = runBlocking {
    val blocking = measureTime {
        coroutineScope {
            repeat(3) { launch { Thread.sleep(1000) } } // blocks the only thread
        }
    }
    println("Thread.sleep in runBlocking: ${blocking.inWholeMilliseconds / 100 * 100} ms")

    val suspending = measureTime {
        coroutineScope {
            repeat(3) { launch { delay(1000) } } // suspends, frees the thread
        }
    }
    println("delay in runBlocking:        ${suspending.inWholeMilliseconds / 100 * 100} ms")

    val offloaded = measureTime {
        coroutineScope {
            repeat(3) { launch(Dispatchers.IO) { Thread.sleep(1000) } }
        }
    }
    println("Thread.sleep on IO:          ${offloaded.inWholeMilliseconds / 100 * 100} ms")
}
Thread.sleep in runBlocking: 3000 ms
delay in runBlocking:        1000 ms
Thread.sleep on IO:          1000 ms

The three Thread.sleep coroutines ran one after another because each one held the only thread. On a UI thread, that's a frozen window.

Switching threads with withContext

withContext(dispatcher) { ... } runs a block on another dispatcher, suspends the caller until the block finishes, and returns its result. When it returns, the caller continues on its original dispatcher.

The recommended pattern is to make each function responsible for its own threading. A function that does blocking I/O switches to IO itself, so callers can call it from anywhere, including the UI thread. Such a function is called main-safe:

import kotlinx.coroutines.*
import java.io.File

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

// main-safe: callers can use it from any dispatcher
suspend fun readConfig(path: String): String = withContext(Dispatchers.IO) {
    log("reading config")
    File(path).readText()
}

suspend fun countWords(text: String): Int = withContext(Dispatchers.Default) {
    log("counting words")
    text.split(Regex("""\s+""")).count { it.isNotEmpty() }
}

fun main() = runBlocking {
    val f = File.createTempFile("config", ".txt").apply {
        writeText("name = demo\nport = 8080\n")
        deleteOnExit()
    }
    log("start")
    val text = readConfig(f.path)
    val words = countWords(text)
    log("back in runBlocking: $words words")
}
[main] start
[DefaultDispatcher-worker-1] reading config
[DefaultDispatcher-worker-1] counting words
[main] back in runBlocking: 6 words

Both withContext calls ran on the same worker thread. Because IO and Default share threads, switching between them often doesn't move to another thread at all, only the accounting of "how many threads does IO use" changes. That makes withContext(Dispatchers.IO) cheap to call even from code that already runs on Default.

withContext is also cheap when the requested dispatcher is the one you're already on: it runs the block directly without dispatching.

Dispatchers.Main: the UI thread

UI toolkits allow UI objects to be touched only from one thread. Dispatchers.Main is that thread. It is not part of kotlinx-coroutines-core; you get it by adding the module for your platform:

dependencies {
    // Android
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0")
    // or Swing
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.11.0")
    // or JavaFX
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-javafx:1.11.0")
}

Using Dispatchers.Main without one of them throws IllegalStateException: Module with the Main dispatcher is missing.

The typical UI flow is: start on Main, switch to IO for slow work, come back to Main to update the UI. With a main-safe function the switching is invisible at the call site. Here with Swing:

import kotlinx.coroutines.*
import kotlinx.coroutines.swing.Swing
import javax.swing.SwingUtilities

fun log(msg: String) =
    println("[${Thread.currentThread().name}] isEDT=${SwingUtilities.isEventDispatchThread()} $msg")

suspend fun loadUser(id: Int): String = withContext(Dispatchers.IO) {
    log("loading user $id")
    Thread.sleep(200) // pretend this is a slow HTTP or DB call
    "User #$id"
}

fun main() = runBlocking {
    // Dispatchers.Main is Swing's event dispatch thread when
    // kotlinx-coroutines-swing is on the classpath
    println("Main is Swing: ${Dispatchers.Main == Dispatchers.Swing}")
    withContext(Dispatchers.Main) {
        log("show spinner")
        val user = loadUser(7)
        log("update label: $user") // back on the UI thread
    }
}
Main is Swing: true
[AWT-EventQueue-0] isEDT=true show spinner
[DefaultDispatcher-worker-1] isEDT=false loading user 7
[AWT-EventQueue-0] isEDT=true update label: User #7

On Android you rarely write withContext(Dispatchers.Main) yourself: lifecycleScope and viewModelScope already use Dispatchers.Main.immediate. The immediate variant skips dispatching when the code is already on the main thread, so a coroutine started from a click handler begins running right away instead of being posted to the end of the event queue.

Dispatchers.Unconfined

Unconfined doesn't pick a thread at all. A coroutine starts in the thread that launched it and, after a suspension, continues in whatever thread resumed it:

import kotlinx.coroutines.*

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

fun main() = runBlocking<Unit> {
    launch(Dispatchers.Unconfined) {
        log("Unconfined: before delay")
        delay(100)
        log("Unconfined: after delay")
    }
    launch {
        log("runBlocking: before delay")
        delay(200)
        log("runBlocking: after delay")
    }
}
[main] Unconfined: before delay
[main] runBlocking: before delay
[kotlinx.coroutines.DefaultExecutor] Unconfined: after delay
[main] runBlocking: after delay

After delay, the unconfined coroutine woke up on the internal timer thread kotlinx.coroutines.DefaultExecutor. That's almost never what you want in application code: you can't know which thread you're on. Its legitimate uses are low-level, such as code that must run immediately in the caller's frame and doesn't care about threads afterwards. For tests, use kotlinx-coroutines-test instead.

Limiting parallelism

dispatcher.limitedParallelism(n) returns a view of a dispatcher that runs at most n coroutines at the same time. It doesn't create threads; it borrows them from the underlying dispatcher.

Common uses:

import kotlinx.coroutines.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.time.measureTime

suspend fun run(name: String, dispatcher: CoroutineDispatcher, tasks: Int) {
    val threads = ConcurrentHashMap.newKeySet<String>()
    val t = measureTime {
        coroutineScope {
            repeat(tasks) {
                launch(dispatcher) {
                    threads += Thread.currentThread().name
                    Thread.sleep(500)
                }
            }
        }
    }
    println("%-28s %4d ms, %3d threads".format(name, t.inWholeMilliseconds / 100 * 100, threads.size))
}

fun main() = runBlocking {
    val db = Dispatchers.IO.limitedParallelism(4, "db")
    val files = Dispatchers.IO.limitedParallelism(200, "files")
    val cpu = Dispatchers.Default.limitedParallelism(2)
    run("IO.limitedParallelism(4)", db, 8)
    run("IO.limitedParallelism(200)", files, 200)
    run("Default.limitedParallelism(2)", cpu, 4)
}
IO.limitedParallelism(4)     1000 ms,   4 threads
IO.limitedParallelism(200)    500 ms, 200 threads
Default.limitedParallelism(2) 1000 ms,   2 threads

Note the second line: Dispatchers.IO is elastic. A view of IO may exceed the 64-thread limit of IO itself, because each view gets its own budget. That's how you give a component that legitimately needs many blocking threads its own capacity without raising the global limit. Views of Default can't exceed the number of Default threads.

The optional second argument ("db") is a name used in toString(), which makes the view easier to recognize in logs and debuggers.

Custom dispatchers

Any java.util.concurrent.Executor can be turned into a dispatcher with asCoroutineDispatcher(). Use this when you need threads with specific names, priorities or daemon status, or when integrating with an existing thread pool.

A dispatcher created from an ExecutorService owns threads, so it must be closed. It implements Closeable, which means use works:

import kotlinx.coroutines.*
import java.util.concurrent.Executors
import kotlin.time.measureTime

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

fun main() = runBlocking {
    // a fixed pool of 3 named threads
    var n = 0
    val pool = Executors.newFixedThreadPool(3) { r -> Thread(r, "worker-${++n}") }
        .asCoroutineDispatcher()

    pool.use { dispatcher ->
        val results = (1..6).map { i ->
            async(dispatcher) {
                log("task $i")
                i * i
            }
        }.awaitAll()
        println(results)
    } // use {} closes the dispatcher and shuts down its threads

    // a virtual thread per task (JDK 21+)
    Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher().use { vt ->
        val t = measureTime {
            coroutineScope {
                repeat(10_000) {
                    launch(vt) { Thread.sleep(1000) } // blocking, but cheap
                }
            }
        }
        println("10,000 blocking tasks on virtual threads: ${t.inWholeMilliseconds / 100 * 100} ms")
    }
}

Example output (the task-to-thread assignment varies):

[worker-1] task 1
[worker-2] task 2
[worker-3] task 3
[worker-1] task 4
[worker-1] task 5
[worker-1] task 6
[1, 4, 9, 16, 25, 36]
10,000 blocking tasks on virtual threads: 1000 ms

The virtual-thread dispatcher is attractive for code that makes lots of blocking calls you can't rewrite: each task gets its own cheap virtual thread, and a blocked virtual thread doesn't hold an OS thread. 10,000 one-second sleeps finished in about one second. For your own CPU-bound code, stick to Dispatchers.Default.

There are also newSingleThreadContext("name") and newFixedThreadPoolContext(n, "name"). They are marked as delicate APIs, and the library recommends limitedParallelism on the shared dispatchers instead, because separate pools waste threads and must be closed.

Don't create a new dispatcher per request or per call. Create it once (for example as a property of a long-lived object), and close it on shutdown (see Signals and graceful shutdown). A forgotten pool keeps non-daemon threads alive and prevents the JVM from exiting.

ThreadLocal values

Libraries like logging MDC, security contexts and transaction managers store data in ThreadLocal. A coroutine can hop between threads, so a value set on one thread is not visible after the coroutine resumes on another.

ThreadLocal.asContextElement(value) creates a context element that sets the thread-local every time the coroutine resumes on any thread, and restores the previous value when it suspends:

import kotlinx.coroutines.*

val requestId = ThreadLocal<String>()

fun log(msg: String) =
    println("[${Thread.currentThread().name}] requestId=${requestId.get()} $msg")

fun main() = runBlocking {
    requestId.set("main")
    withContext(Dispatchers.Default) {
        log("plain ThreadLocal is lost on another thread")
    }
    withContext(Dispatchers.Default + requestId.asContextElement("req-42")) {
        log("before delay")
        delay(10)
        withContext(Dispatchers.IO) {
            log("still set after switching dispatchers")
        }
    }
    log("restored in runBlocking")
}
[DefaultDispatcher-worker-1] requestId=null plain ThreadLocal is lost on another thread
[DefaultDispatcher-worker-1] requestId=req-42 before delay
[DefaultDispatcher-worker-1] requestId=req-42 still set after switching dispatchers
[main] requestId=main restored in runBlocking

Changing the thread-local with set() inside the coroutine is not propagated: the element always installs the value it was created with. To change it, start a new withContext(requestId.asContextElement(newValue)). For SLF4J's MDC there's a ready-made element, MDCContext(), in kotlinx-coroutines-slf4j (see Logging).

Choosing a dispatcher

Work Dispatcher
calling suspending APIs (Ktor, delay, flows, channels) any; usually just inherit the caller's
CPU-heavy computation Dispatchers.Default
blocking I/O (JDBC, java.io, blocking SDKs) Dispatchers.IO, or runInterruptible(Dispatchers.IO) to make it cancellable (see Cancellation and timeouts)
at most N concurrent operations on a resource Dispatchers.IO.limitedParallelism(N)
mutable state accessed from one place at a time limitedParallelism(1)
updating UI Dispatchers.Main / Dispatchers.Main.immediate
many blocking calls you can't rewrite (JDK 21+) Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher()
collecting a flow whose upstream blocks flowOn(Dispatchers.IO) on the flow (see Flows)

Gotchas

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents