Coroutine overhead
- Kotlin course
- Expert
- Lesson 41/47
- 5 min
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
// add the coroInfo function
fun main() {
// print the coroutine info
}Sample solution
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
runBlocking { launch { ____ } }
runBlocking { launch { delay(100) } }
Explanation: delay(100) suspends the coroutine; not Thread.sleep.
2 What does a coroutine reduce compared to a thread?
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 |