What are Coroutines

Lightweight Threads

A coroutine is a piece of code that can pause (suspend) and resume later without blocking the thread it runs on. While one coroutine waits for a network reply or a timer, the same thread runs other coroutines. That is why you can start 100,000 coroutines on a laptop, but not 100,000 threads.

ThreadCoroutine
Managed byOperating systemKotlin runtime (library)
Memory~1 MB stack eacha few hundred bytes (an object on the heap)
Waitingblocks the thread (Thread.sleep)suspends, thread is free (delay)
Switching costexpensive context switchcheap function call
Cancellationhard (interrupt flags)built in, cooperative
Code stylecallbacks / futuresnormal sequential code

How Suspension Works

Thread "main"
 ├─ coroutine A: fetchUser()  ── calls delay/network ──► SUSPENDED (state saved)
 ├─ coroutine B: runs now on the same thread
 ├─ coroutine B: suspends
 └─ coroutine A: reply arrived ─► RESUMED from the saved point

One thread, many coroutines: they take turns at every suspension point.

The compiler turns every suspend function into a state machine. Local variables are stored in a continuation object, so the function can stop at a suspension point and continue later, maybe on another thread.

100,000 Coroutines

Example

Each coroutine waits 100 ms with delay. They all wait at the same time, so the whole program takes about 100 ms, not 10,000 seconds.

import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis

fun main() = runBlocking {
    var finished = 0
    val time = measureTimeMillis {
        coroutineScope {
            repeat(100_000) {
                launch {
                    delay(100)
                    finished++
                }
            }
        }
    }
    println("Finished coroutines: $finished")
    println("Took less than 3 seconds: ${time < 3000}")
}

Output

Finished coroutines: 100000
Took less than 3 seconds: true

Adding Coroutines to a Project

Coroutines are a library, not part of the standard library. Android projects that use lifecycle or Room already get it.

// build.gradle.kts
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
    // Android: adds Dispatchers.Main
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
}

Note: Kotlin 1.3+ ships the language support (suspend); everything else (launch, Flow, dispatchers) comes from kotlinx.coroutines.