Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 134 ยท Coroutines

Dispatchers and Coroutine Context

Understand Kotlin coroutine dispatchers and CoroutineContext - Default, IO, Main, Unconfined, limitedParallelism, withContext, CoroutineName and how contexts combine, with runnable examples.

A coroutine is a piece of code that can pause and resume. But which thread runs it? That question is answered by the dispatcher, one element of a larger structure called the coroutine context. If you have ever wondered why runBlocking stays on main, why heavy work belongs on Dispatchers.Default, or what withContext(Dispatchers.IO) is for, this lesson is the answer.

You will learn what a context is, how elements combine with +, the dispatchers you can choose, and how to move work between them. It follows cancellation and timeouts and prepares exceptions in coroutines, because handlers are context elements too.

The coroutine context

Every coroutine has a CoroutineContext: a small set of elements, each identified by a key. The ones you meet most often:

  • Job: the lifecycle handle (see structured concurrency).
  • CoroutineDispatcher: decides the thread(s).
  • CoroutineName: a label that helps debugging.
  • CoroutineExceptionHandler: a last-resort handler for uncaught errors.

You read an element by indexing the context with its key, and you combine elements with +. When two elements have the same key, the right-hand one wins.

Kotlin Reading and combining context elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A new coroutine inherits the context of its parent, then the elements you pass to launch or async override it. A fresh Job is always created for the child, so each coroutine has its own handle while keeping the parent link. This is why a plain launch { } inside runBlocking runs on the same thread as runBlocking itself: it inherited the dispatcher.

What a dispatcher does

A dispatcher takes the continuation of a coroutine (the code after the last suspension point) and decides where to run it. Each time a coroutine resumes after delay or await, the dispatcher schedules it again. The standard ones:

Dispatcher Threads Use for
Dispatchers.Default A shared pool, one thread per CPU core (at least 2) CPU-heavy work: sorting, parsing, computing
Dispatchers.IO A shared elastic pool, up to 64 threads by default Blocking calls: files, JDBC, sockets
Dispatchers.Main The UI thread (Android, Compose Desktop, JavaFX) UI updates; needs a platform artifact
Dispatchers.Unconfined The caller's thread, then whatever resumes it Special cases and tests; rarely in app code

Default and IO share their threads: switching between them does not always change threads, so it is cheap. Let us see which thread runs what. Thread names inside the shared pool carry a number that can vary between runs, so we print only the stable part.

Kotlin Where does the code run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output order of the three non-main launches is not guaranteed, because they run in parallel; treat each line on its own. What matters: plain launch stays on main, Default and IO leave it for the shared pool.

runBlocking creates an event loop on the calling thread and blocks that thread until its coroutines finish. It is meant for main functions and tests, never for code that already runs in a coroutine.

Dispatchers.Default for computing

The default pool has as many threads as cores, so CPU-bound coroutines get real parallelism without oversubscribing the machine. Do not run blocking calls on it: a handful of blocked threads can starve every other coroutine that uses the pool.

Dispatchers.IO for blocking work

Reading a file, calling a database over JDBC or waiting on a socket blocks a thread. Dispatchers.IO expects that: it grows its pool to cope, so a hundred blocking calls do not starve the CPU-bound work in Default. The real fix for blocking code is a non-blocking API, but when you have only blocking libraries (most Java ones), IO is the right place to wrap them.

Dispatchers.Main

On Android and desktop UI platforms, Main is the thread that owns the screen. On a plain JVM without a UI library, using it is an error. Our runner has no UI module, so you can see the real message:

Kotlin Dispatchers.Main without a UI (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The exception says that the module with the Main dispatcher is missing. In a real Android app the kotlinx-coroutines-android artifact provides it; on the server you simply never use Main.

Switching threads with withContext

withContext(context) { ... } runs a block in a different context and suspends the caller until it finishes, returning the block's value. It is the standard way to say "this part belongs on another dispatcher" without starting a new coroutine you have to join.

Kotlin withContext hops and returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The function starts and ends on main and does the heavy part on the pool. Callers do not need to know: a suspend function that switches internally with withContext is called main-safe, and this is the convention to follow. Callers (a UI, a service) should be free to call it from any thread.

withContext(Dispatchers.Default) also takes part in structured concurrency and cancellation: if the outer coroutine is cancelled, the block is cancelled too.

limitedParallelism

Sometimes you want a dispatcher that runs at most N coroutines at a time, for example "never more than 4 database calls at once" or "use only one thread so state needs no lock". dispatcher.limitedParallelism(n) creates a view of an existing dispatcher that never uses more than n threads at the same time, without creating threads of its own.

Kotlin Limiting parallelism

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

With a limit of 2 no more than two tasks ever ran at once, and with 1 they ran strictly one after another. A dispatcher with parallelism 1 is a lightweight alternative to a dedicated single thread: code that runs on it is never executed in parallel with other code on the same dispatcher, which makes it a good place for state that is not thread-safe (see shared mutable state). Note that a coroutine that suspends lets another one run on the same dispatcher in between; "single thread" does not mean "one coroutine at a time from start to finish".

Your own thread pool

If you really need your own threads (a legacy library that wants a specific thread, a bounded pool for one resource), convert a Java executor and close it when you are done:

Kotlin A dispatcher from an executor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Forgetting close() leaves non-daemon threads alive and the JVM does not exit. Prefer limitedParallelism on a built-in dispatcher unless you need dedicated threads.

Unconfined and why to avoid it

Dispatchers.Unconfined starts the coroutine in the caller's thread and, after a suspension, resumes it in whatever thread the suspending function used. The thread is unpredictable, which is dangerous for anything but tests and very special cases.

Kotlin Unconfined switches threads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The unconfined coroutine moved from main to a different thread because delay resumes it from the library's timer thread. The inherited dispatcher stayed on main throughout. Use Unconfined only when you understand this, for example in a performance-sensitive operator.

Debugging: names and thread names

When many coroutines run, CoroutineName makes logs readable. You can also start the JVM with -Dkotlinx.coroutines.debug to have thread names show @coroutine#1 suffixes; we cannot pass JVM flags here, so add the name yourself:

Kotlin Naming coroutines for logs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

log must be a suspend function to read the context with currentCoroutineContext(): a plain function has no coroutine to ask. The two async lines may appear in either order, since both coroutines wait the same 10 ms; the sum is always 3.

Rules of thumb

  • Do not choose a dispatcher at every call. Let coroutines inherit, and switch with withContext at the boundary where the nature of the work changes.
  • CPU work: Default. Blocking calls: IO. UI: Main.
  • Make suspend functions main-safe: they pick their own dispatcher internally.
  • Pass dispatchers as constructor parameters in classes so tests can replace them.
  • Use limitedParallelism(n) to bound concurrency; use limitedParallelism(1) to serialize access to unprotected state.
  • Never run long blocking code on Default.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A plain launch { } inside runBlocking on main runs on which thread?

    A child coroutine inherits the context, including the dispatcher, from its parent unless you override it.
  2. 2. Which dispatcher is meant for blocking operations such as file or JDBC access?

    Dispatchers.IO uses an elastic pool that tolerates blocked threads; Default is sized for CPU-bound work.
  3. 3. What does withContext(Dispatchers.Default) { ... } do?

    withContext switches context for the block only, suspends instead of blocking, and returns the result.
  4. 4. What does Dispatchers.Default.limitedParallelism(1) give you?

    It limits concurrent execution to one thread at a time without creating a thread. A suspended coroutine can still be interleaved with others.
  5. 5. In ctx + CoroutineName("b"), where ctx already contains CoroutineName("a"), what is the name of the result?

    Elements with the same key are replaced by the one on the right.

Summary

  • A coroutine's context is a set of keyed elements (Job, dispatcher, CoroutineName, handler); combine them with +, the right side wins.
  • Children inherit the parent's context; the child gets its own Job.
  • Default is for CPU work, IO for blocking calls, Main for the UI; Unconfined is a special case.
  • withContext switches dispatcher for a block and returns its result; make suspend functions main-safe.
  • limitedParallelism(n) bounds concurrency; 1 serializes access to state.
  • Executor-based dispatchers must be closed.

Next: Exceptions in Coroutines