Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Dispatchers and Thread Control | Getting Started with Coroutines
Kotlin Concurrency Fundamentals

bookDispatchers and Thread Control

Deslize para mostrar o menu

Understanding where and how your coroutines execute is essential for writing performant and safe concurrent code. In Kotlin, a dispatcher determines the thread or thread pool that a coroutine uses for its execution. The most commonly used dispatchers are Default, IO, and Main. Each is optimized for specific types of work:

  • Default Dispatcher: Used for CPU-intensive tasks such as sorting large lists, performing calculations, or processing data;
  • IO Dispatcher: Designed for offloading blocking IO operations like reading from or writing to files, making network requests, or accessing databases;
  • Main Dispatcher: Confines coroutine execution to the main thread, which is necessary for updating UI elements in Android apps.

Choosing the right dispatcher not only improves performance but also ensures your app remains responsive and avoids common pitfalls like UI freezes or thread starvation.

CoroutineDispatchersExample.kt

CoroutineDispatchersExample.kt

copy
12345678910111213141516171819202122
package com.example import kotlinx.coroutines.* fun main() = runBlocking { println("Main program starts: ${Thread.currentThread().name}") launch(Dispatchers.Default) { println("Default dispatcher: ${Thread.currentThread().name}") } launch(Dispatchers.IO) { println("IO dispatcher: ${Thread.currentThread().name}") } // Uncomment the following if running in an environment with a main/UI thread (e.g., Android) // launch(Dispatchers.Main) { // println("Main dispatcher: ${Thread.currentThread().name}") // } println("Main program ends: ${Thread.currentThread().name}") }

When you launch a coroutine, the dispatcher you choose directly impacts where that coroutine will run. For example, using Dispatchers.Default places your coroutine on a shared pool of background threads optimized for CPU-bound work. Dispatchers.IO uses a pool of threads designed for IO-bound operations, allowing you to perform blocking tasks without affecting the responsiveness of your application. On Android, Dispatchers.Main ensures that any code interacting with the UI runs on the main thread, preventing concurrency issues and UI exceptions.

Best practices for dispatcher selection include:

  • Use Dispatchers.Default for tasks that require significant CPU resources and do not involve blocking operations;
  • Use Dispatchers.IO for network requests, file operations, or database access to avoid blocking the main thread;
  • Use Dispatchers.Main for updating the UI or handling user interactions in Android applications.

By thoughtfully choosing dispatchers, you can write efficient, maintainable, and safe concurrent code that leverages the strengths of Kotlin coroutines.

question mark

Which dispatcher is recommended for network or disk operations in Kotlin coroutines?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 4

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 2. Capítulo 4
some-alt