CodeBlanks Logo Icon CodeBlanks

Coroutine overhead

Learn coroutine and thread cost.

What is coroutine overhead?

A coroutine is a lightweight, suspendable task in Kotlin. It is far cheaper than a thread; thousands can run at once.

Still, a coroutine is not free: each carries a Job and a state object. Dispatchers.Default is for CPU work, Dispatchers.IO for file or network work. A wrong choice (heavy CPU on IO) is inefficient. runBlocking is used as a bridge. The coroInfo model in this lesson shows the concept.

Choosing a dispatcher

A dispatcher decides which thread pool a coroutine runs on. A wrong choice lowers performance.

Dispatchers.Default is for CPU-bound work (numeric compute). Dispatchers.IO is for file and network I/O. Dispatchers.Main is on the UI thread. Putting CPU work on IO saturates the pool; putting I/O on Default blocks threads. The right match is critical for both throughput and latency.

Practice Write coroInfo

Define fun coroInfo(): String. It should return "coroutine". In main, write println(coroInfo()).

Starter code

Main.kt
// add the coroInfo function

fun main() {
    // print the coroutine info
}

Sample solution

Main.kt
fun coroInfo(): String = "coroutine"
fun main() {
    println(coroInfo())
}

Expected output

coroutine

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the runBlocking body

Question
runBlocking { launch { ____ } }
Answer
runBlocking { launch { delay(100) } }

Explanation: delay(100) suspends the coroutine; not Thread.sleep.

2 What does a coroutine reduce compared to a thread?

Main.kt
A coroutine lowers thread cost.
  • Disk latency
  • CPU cache hit rate
  • Thread creation cost Correct answer
  • Memory bandwidth

Explanation: A coroutine greatly reduces thread creation cost.

3 Match the coroutine parts

Term Meaning
coroutine Light task
Dispatchers.Default CPU-bound work
Dispatchers.IO I/O work
runBlocking Bridge

All lessons in Expert