Coroutines are lightweight concurrent tasks designed for structured async I/O—Kotlin's alternative to callback chains in JavaScript and thread pools in Java. On Gradle projects you use kotlinx-coroutines; the playground simulates concurrency with threads.
Concepts
suspendfunctions can pause without blocking a threadCoroutineScopeand structured concurrency cancel child work when parents failasync/awaitandlaunchschedule work on dispatchers
runBlocking (local / Gradle only)
In Android Studio or a Gradle module with coroutines on the classpath, runBlocking { } bridges blocking main to suspend functions for demos and tests. Do not use runBlocking on production request threads—prefer suspend all the way up.
// Local Gradle — not in playground
runBlocking {
val result = fetchUser()
println(result)
}
This lesson's runnable code uses kotlin.concurrent.thread and Thread.sleep to preview overlapping work without the coroutines library.
Important interview questions and answers
- Q: Coroutine vs thread?
A: Coroutines are cooperatively scheduled on thread pools—cheaper to spawn thousands for I/O-bound work; threads are OS resources with higher overhead. - Q: What is runBlocking for?
A: Blocking entry point that runs a coroutine scope to completion—fine formainand tests, not for reactive server threads.
Self-check
- Why avoid runBlocking on a servlet thread?
- What keyword marks a function that can suspend?
Tip: Real projects add kotlinx-coroutines and use runBlocking only in main or tests—not on HTTP worker threads.
Interview prep
- runBlocking in servers?
Avoid on request threads—blocks and hurts scalability.
- Coroutines vs threads?
Lightweight tasks with suspend; structured cancellation.