0
0
KotlinConceptBeginner · 3 min read

What is Dispatchers.Default in Kotlin: Explanation and Example

Dispatchers.Default in Kotlin is a built-in coroutine dispatcher optimized for CPU-intensive tasks. It uses a shared pool of background threads to run coroutines efficiently without blocking the main thread.
⚙️

How It Works

Imagine you have a kitchen with several cooks who can prepare meals at the same time. Dispatchers.Default is like this kitchen's team of cooks, ready to handle multiple cooking tasks (coroutines) that need a lot of effort (CPU work).

When you launch a coroutine with Dispatchers.Default, Kotlin assigns it to one of these background threads. This way, your app's main thread stays free to handle user actions, while heavy tasks run smoothly in the background.

This dispatcher automatically manages the number of threads based on your device's CPU cores, so it balances work efficiently without you needing to set up threads manually.

💻

Example

This example shows how to launch a coroutine on Dispatchers.Default to perform a CPU-heavy calculation without blocking the main thread.

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    println("Main thread: ${Thread.currentThread().name}")

    val job = launch(Dispatchers.Default) {
        println("Running on: ${Thread.currentThread().name}")
        // Simulate CPU-intensive task
        var sum = 0L
        for (i in 1..1_000_000L) {
            sum += i
        }
        println("Sum is $sum")
    }

    job.join() // Wait for coroutine to finish
    println("Done")
}
Output
Main thread: main Running on: DefaultDispatcher-worker-1 Sum is 500000500000 Done
🎯

When to Use

Use Dispatchers.Default when you have tasks that need a lot of CPU power, like sorting large lists, processing data, or running complex calculations. It helps keep your app responsive by moving these heavy tasks off the main thread.

For example, in an app that processes images or performs mathematical computations, launching coroutines with Dispatchers.Default ensures these operations don't freeze the user interface.

Key Points

  • Dispatchers.Default is optimized for CPU-intensive work.
  • It uses a shared pool of background threads matching CPU cores.
  • Helps keep the main thread free for UI and user interactions.
  • Automatically manages thread count for efficiency.
  • Not suitable for IO tasks; use Dispatchers.IO for those.

Key Takeaways

Dispatchers.Default runs CPU-heavy coroutines on background threads.
It keeps the main thread free to keep apps responsive.
Automatically adjusts threads based on CPU cores for efficiency.
Use it for calculations, data processing, and other intensive tasks.
For IO tasks, prefer Dispatchers.IO instead.