Part 14 / Stage 3
Coroutines and structured concurrency
Goal: Write concurrent Kotlin without blocking threads or juggling callbacks --
suspendfunctions, the coroutine builders (runBlocking,launch,async), structured concurrency and scopes, cancellation, dispatchers, and exception handling in coroutines. Time: ~7 hours · Level: comfortable with Part 13 (generics) --async<T>andDeferred<T>are ordinary generic types, nothing new there -- and with Stage 2's higher-order functions (Part 10), since coroutine builders are higher-order functions that take a lambda.
🔍 Going deeper:
DESIGN-NOTES.mdexplains why coroutines sit here, right after generics:launch/asyncare generic higher-order functions, andsuspendfunctions compose exactly like ordinary ones once lambdas-as-values feel natural.
What you will learn
suspendfunctions: what "pausing without blocking" actually means, versusThread.sleep- The coroutine builders:
runBlocking(bridging into the coroutine world),launch(fire-and-forget),async/await(a result you read back later) - Structured concurrency:
coroutineScopewaits for every child and propagates failure;supervisorScopeisolates one child's failure from its siblings - Cancellation is cooperative: suspension points,
isActive,withTimeout/withTimeoutOrNull, and why afinallyblock still runs - Dispatchers:
Defaultfor CPU work,IOfor blocking calls,withContextto switch, and why thousands of coroutines don't mean thousands of threads - Exception handling in coroutines: plain
try/catch,CoroutineExceptionHandler+SupervisorJob, and therunCatchingpitfall withCancellationException - Building a concurrent task runner that processes a batch of tasks at once, in isolation from each other's failures, without blocking a single OS thread
How this part's code runs
Coroutines are not part of the Kotlin standard library -- they're a separate library,
kotlinx-coroutines-core, that has to be on the classpath. This course has used nothing but
kotlinc/java directly since Stage 1 (no Gradle), so that dependency is fetched once, by hand,
and checked in under libs/:
$ curl -sL -o libs/kotlinx-coroutines-core-jvm-1.11.0.jar \
https://repo1.maven.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core-jvm/1.11.0/kotlinx-coroutines-core-jvm-1.11.0.jar
$ shasum -a 256 libs/kotlinx-coroutines-core-jvm-1.11.0.jar
d1d75aa01dffbb4d1c520e67e4c4e7f5f6174718e7cb4632412503f2f0e604fa libs/kotlinx-coroutines-core-jvm-1.11.0.jar
That checksum matches the one Maven Central publishes for this exact artifact
(kotlinx-coroutines-core-jvm-1.11.0.jar.sha256), confirming the download wasn't corrupted or
tampered with. 1.11.0 is the latest stable release as of this writing, and it ran cleanly on the
kotlinc 2.4.21 / JDK 21 toolchain this course already verified in ../../TOOLING.md -- no
other install step was needed.
Every example and solution here compiles and runs with the coroutines jar on the classpath at both steps:
$ kotlinc 07_concurrent_task_runner.kt -cp ../libs/kotlinx-coroutines-core-jvm-1.11.0.jar \
-include-runtime -d 07_concurrent_task_runner.jar
$ java -cp "07_concurrent_task_runner.jar:../libs/kotlinx-coroutines-core-jvm-1.11.0.jar" \
_07_concurrent_task_runnerKt
One wrinkle: java -jar ignores any -cp you pass alongside it, so running a jar that needs an
extra jar on the classpath (like this one needs the coroutines jar) means naming the actual
class explicitly with java -cp "...:..." <ClassName> instead of java -jar. Kotlin names that
class after the file: lowercase-letter file names get their first letter capitalized plus Kt
(ex01.kt → Ex01Kt); file names starting with a digit get an underscore prepended instead
(07_concurrent_task_runner.kt → _07_concurrent_task_runnerKt) because a class name can't
start with a digit. Every command in this README and in exercises.md was run for real with the
exact class name that produced; the rule above is only here so you can derive it yourself for
your own files.
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Every exercise is one file with a top-level fun main() = runBlocking { ... }, using suspend
functions, coroutine builders, structured concurrency, cancellation, dispatchers and exception
handling from this part, on top of everything Stage 1-2 and Part 13 covered. Compile and run each
one with the coroutines jar on the classpath at both steps -- see "How this part's code runs" in
README.md for the exact commands and how to work out each file's generated class
name.
Exercise 1: IRCTC PNR status check
Scenario: an IRCTC-style status page checks two PNRs, one after another, and times how long
both checks took.
What to do: write suspend fun checkPnrStatus(pnr: String): String that delays 200ms and
returns a status string. Call it twice inside runBlocking, printing each result, and measure
the total time with measureTimeMillis (from kotlin.system).
Sample output:
PNR-4821001: CNF/B4/22
PNR-4821002: CNF/B4/22
Checked 2 PNRs in 412ms (varies, ~400ms)
💡 Hint: two sequential 200ms suspend calls take about 400ms total -- there's no overlap
unless you start them with async (Exercise 2 is about exactly that distinction).
Exercise 2: launch vs. async
Scenario: placing an order needs to (a) log the UPI transaction, which nobody needs to wait
on the result of, and (b) compute the total bill, whose result the checkout screen actually
needs.
What to do: write suspend fun logTransaction(txnId: String) (delays 50ms, prints a log
line, returns nothing useful) and suspend fun computeTotal(amounts: List<Int>): Int (delays
100ms, returns the sum). Start the log with launch, printing job.isActive right after
starting it (before join()); get the total with async/await().
Sample output:
log job still running right after launch: true
UPI txn T-55210 logged
Total bill: ₹810
💡 Hint: launch returns before its body has run anything -- that's why isActive reads
true immediately after starting it, not after it's done.
Exercise 3: Bank confirmation, two ways
Scenario: a payment needs confirmation from three partner banks. First, try it as "all three
must succeed or the whole payment fails." Then try it as "each bank's result matters on its
own, and one declining shouldn't undo the others."
What to do: write suspend fun confirmWithBank(bank: String, delayMs: Long, fail: Boolean = false): String (delays, then returns a confirmation string or throws IllegalStateException,
rethrowing CancellationException if cancelled). Use coroutineScope with three launch
calls, one of them failing, inside a try/catch. Then, separately, use supervisorScope with
three async calls and await() each inside its own try/catch.
Sample output:
--- coroutineScope: one bank failing cancels the others
HDFC confirmed
SBI confirmation cancelled
coroutineScope failed: ICICI declined the payment
--- supervisorScope: each bank's result is handled independently
HDFC confirmed
failed: ICICI declined the payment
SBI confirmed
💡 Hint: give SBI the longest delay in both halves, so it's still running (and gets cancelled) in the first half, but has time to actually finish in the second.
Exercise 4: Stop polling cooperatively
Scenario: a delivery app polls a partner's live location every 100ms in a loop with no other
suspension point between polls besides the delay itself, and needs to stop cleanly when the
user closes the tracking screen. Separately, computing a slow ETA should give up after 200ms
rather than hang.
What to do: write suspend fun CoroutineScope.pollLiveLocation(onUpdate: (Int) -> Unit) that
loops while (isActive), calling onUpdate with an increasing counter and delay(100) between
calls. launch it, let it run for 350ms, then cancelAndJoin() it, with a finally block that
prints a "stopped" message. Separately, wrap a 600ms delay in withTimeoutOrNull(200) and
print the result.
Sample output:
partner location update #0
partner location update #1
partner location update #2
partner location update #3
stopped polling live location
polling job cancelled: true
slow ETA result: null
💡 Hint: isActive is a property of CoroutineScope -- that's why pollLiveLocation needs
to be declared as an extension function on CoroutineScope, not a plain top-level suspend fun.
Exercise 5: Fetch three menus concurrently
Scenario: a restaurant-discovery screen needs three restaurants' menus, each coming from a
(simulated) blocking network call, without the screen waiting three times as long as it needs to.
What to do: write suspend fun fetchMenu(restaurant: String): String that uses
withContext(Dispatchers.IO) to run a Thread.sleep(100) (the "blocking call") and return a
result string. Fetch three restaurants' menus with async/awaitAll().
Sample output:
Trupti Tiffins: menu fetched
Spice Villa: menu fetched
Punjabi Rasoi: menu fetched
💡 Hint: this finishes in roughly 100ms total, not 300ms -- time it yourself with
measureTimeMillis to confirm the three Thread.sleep calls genuinely overlapped on
Dispatchers.IO's pool.
Exercise 6: Notification jobs that don't take each other down
Scenario: a notification scope sends SMS and email independently -- one failing (say, the
SMS gateway is down) shouldn't stop the other, and should just get logged. Separately, a push
notification that gets cancelled mid-send must not be reported as a "failure".
What to do: build a CoroutineScope(SupervisorJob() + handler) with a
CoroutineExceptionHandler that prints "handler logged: ...". launch a job that calls
error(...) (an SMS failure), then a second job that just prints a success message; join()
both, then scope.cancel(). Separately, launch a job that uses runCatching around a 500ms
delay, correctly rethrowing CancellationException from onFailure instead of logging it;
cancel that job after 50ms.
Sample output:
handler logged: SMS gateway unreachable
email notification sent
notification job cancelled cleanly: true
💡 Hint: nothing should print between "email notification sent" and
"notification job cancelled cleanly: true" -- if you see a "notification failed: ..." line,
onFailure isn't rethrowing CancellationException correctly.
Exercise 7: Limit how many tasks run at once
Scenario: the Section 7 task runner currently runs every task at full concurrency; a packing
station only has 2 printers, so at most 2 orders can be printed at the same time.
What to do: write BatchedTaskRunner(maxConcurrent: Int) whose runAll splits the task IDs
into chunks of maxConcurrent (List.chunked), runs each chunk with supervisorScope +
async + awaitAll() the same way Section 7 did, and moves on to the next chunk only once the
current one finishes. Run it on 6 orders with maxConcurrent = 2, each taking ~100ms.
Sample output:
O-2001: slip printed
O-2002: slip printed
O-2003: slip printed
O-2004: slip printed
O-2005: slip printed
O-2006: slip printed
Processed 6 orders, 2 at a time, in 318ms (varies, ~300ms: 3 batches x ~100ms)
💡 Hint: 6 orders at 2-at-a-time is 3 batches; each batch takes ~100ms, so the total should land around 300ms, not 100ms (full concurrency) or 600ms (fully sequential).
Exercise 8: Retry once before giving up
Scenario: one order's packing slip occasionally fails on the first try ("printer buffer
full") but succeeds if retried -- the task runner should retry a failing task exactly once
before reporting it as a real failure.
What to do: write RetryingTaskRunner whose runAll runs each task through a private
runOnce helper that tries up to twice (repeat(2)), printing a retry message and trying again
on the first failure, returning a TaskResult with the error on the second. Use an
AtomicInteger (not a plain shared var) to make exactly one order fail on its first attempt
only, so the retry succeeds.
Sample output:
retrying O-3002 after: printer buffer full
OK O-3001: slip printed
OK O-3002: slip printed
OK O-3003: slip printed
💡 Hint: a plain var shared across coroutines running on Dispatchers.Default (a real
multi-threaded pool) is a genuine data race -- that's exactly why this one uses
java.util.concurrent.atomic.AtomicInteger instead, even for something this small.
Show the solutions for Part 14 (8 files)
solutions/ex01.kt
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun checkPnrStatus(pnr: String): String {
delay(200)
return "$pnr: CNF/B4/22"
}
fun main() = runBlocking {
val time = measureTimeMillis {
println(checkPnrStatus("PNR-4821001"))
println(checkPnrStatus("PNR-4821002"))
}
println("Checked 2 PNRs in ${time}ms (varies, ~400ms)")
}
solutions/ex02.kt
import kotlinx.coroutines.*
suspend fun logTransaction(txnId: String) {
delay(50)
println("UPI txn $txnId logged")
}
suspend fun computeTotal(amounts: List<Int>): Int {
delay(100)
return amounts.sum()
}
fun main() = runBlocking {
val logJob = launch { logTransaction("T-55210") }
println("log job still running right after launch: ${logJob.isActive}")
logJob.join()
val totalDeferred = async { computeTotal(listOf(420, 180, 210)) }
println("Total bill: ₹${totalDeferred.await()}")
}
solutions/ex03.kt
import kotlinx.coroutines.*
suspend fun confirmWithBank(bank: String, delayMs: Long, fail: Boolean = false): String {
try {
delay(delayMs)
if (fail) throw IllegalStateException("$bank declined the payment")
return "$bank confirmed"
} catch (e: CancellationException) {
println(" $bank confirmation cancelled")
throw e
}
}
fun main() = runBlocking {
println("--- coroutineScope: one bank failing cancels the others")
try {
coroutineScope {
launch { println(" " + confirmWithBank("HDFC", 100)) }
launch { confirmWithBank("ICICI", 150, fail = true) }
launch { println(" " + confirmWithBank("SBI", 500)) }
}
} catch (e: IllegalStateException) {
println("coroutineScope failed: ${e.message}")
}
println("--- supervisorScope: each bank's result is handled independently")
supervisorScope {
val results = listOf(
Triple("HDFC", 100L, false),
Triple("ICICI", 150L, true),
Triple("SBI", 300L, false),
).map { (bank, ms, fail) -> async { confirmWithBank(bank, ms, fail) } }
results.forEach { deferred ->
try {
println(" " + deferred.await())
} catch (e: IllegalStateException) {
println(" failed: ${e.message}")
}
}
}
}
solutions/ex04.kt
import kotlinx.coroutines.*
suspend fun CoroutineScope.pollLiveLocation(onUpdate: (Int) -> Unit) {
var tick = 0
while (isActive) { // cooperative: checked every loop, not just at delay()
onUpdate(tick)
tick++
delay(100)
}
}
fun main() = runBlocking {
val job = launch {
try {
pollLiveLocation { tick -> println("partner location update #$tick") }
} finally {
println("stopped polling live location")
}
}
delay(350)
job.cancelAndJoin()
println("polling job cancelled: ${job.isCancelled}")
val slowEta = withTimeoutOrNull(200) {
delay(600)
"ETA computed"
}
println("slow ETA result: $slowEta")
}
solutions/ex05.kt
import kotlinx.coroutines.*
suspend fun fetchMenu(restaurant: String): String = withContext(Dispatchers.IO) {
Thread.sleep(100) // pretend blocking network call -- genuinely blocks one IO-dispatcher thread
"$restaurant: menu fetched"
}
fun main() = runBlocking {
val menus = listOf("Trupti Tiffins", "Spice Villa", "Punjabi Rasoi").map { name ->
async { fetchMenu(name) }
}.awaitAll()
menus.forEach { println(it) }
}
solutions/ex06.kt
import kotlinx.coroutines.*
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, e -> println("handler logged: ${e.message}") }
val scope = CoroutineScope(SupervisorJob() + handler)
scope.launch { error("SMS gateway unreachable") }.join()
val emailJob = scope.launch { println("email notification sent") }
emailJob.join()
scope.cancel()
val job = launch {
val result = runCatching {
delay(500)
"push notification sent"
}
result.onFailure { e ->
if (e is CancellationException) throw e // never swallow cancellation
println("notification failed: ${e.message}")
}
result.onSuccess { println(it) }
}
delay(50)
job.cancelAndJoin()
println("notification job cancelled cleanly: ${job.isCancelled}")
}
solutions/ex07.kt
import kotlinx.coroutines.*
data class TaskResult<T>(val taskId: String, val value: T? = null, val error: String? = null) {
val succeeded: Boolean get() = error == null
}
class BatchedTaskRunner(private val maxConcurrent: Int, private val timeoutMs: Long = 500) {
suspend fun <T> runAll(taskIds: List<String>, task: suspend (String) -> T): List<TaskResult<T>> {
val results = mutableListOf<TaskResult<T>>()
for (batch in taskIds.chunked(maxConcurrent)) {
val batchResults = supervisorScope {
batch.map { id ->
async(Dispatchers.Default) {
try {
val value = withTimeout(timeoutMs) { task(id) }
TaskResult(id, value = value)
} catch (e: Exception) {
TaskResult<T>(id, error = e.message ?: "unknown error")
}
}
}.awaitAll()
}
results += batchResults
}
return results
}
}
suspend fun printSlip(orderId: String): String {
delay(100)
return "$orderId: slip printed"
}
fun main() = runBlocking {
val orderIds = listOf("O-2001", "O-2002", "O-2003", "O-2004", "O-2005", "O-2006")
val runner = BatchedTaskRunner(maxConcurrent = 2)
val startedAt = System.currentTimeMillis()
val results = runner.runAll(orderIds, ::printSlip)
val elapsed = System.currentTimeMillis() - startedAt
results.forEach { println(it.value) }
println("Processed ${orderIds.size} orders, 2 at a time, in ${elapsed}ms (varies, ~300ms: 3 batches x ~100ms)")
}
solutions/ex08.kt
import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicInteger
data class TaskResult<T>(val taskId: String, val value: T? = null, val error: String? = null) {
val succeeded: Boolean get() = error == null
}
class RetryingTaskRunner(private val timeoutMs: Long = 500) {
suspend fun <T> runAll(taskIds: List<String>, task: suspend (String) -> T): List<TaskResult<T>> =
supervisorScope {
taskIds.map { id ->
async(Dispatchers.Default) { runOnce(id, task) }
}.awaitAll()
}
private suspend fun <T> runOnce(id: String, task: suspend (String) -> T): TaskResult<T> {
repeat(2) { attempt ->
try {
val value = withTimeout(timeoutMs) { task(id) }
return TaskResult(id, value = value)
} catch (e: Exception) {
if (attempt == 1) return TaskResult(id, error = e.message ?: "unknown error")
println(" retrying $id after: ${e.message}")
}
}
return TaskResult(id, error = "unreachable")
}
}
val attemptsForFlaky = AtomicInteger(0)
suspend fun flakyPrint(orderId: String): String {
delay(80)
if (orderId == "O-3002" && attemptsForFlaky.getAndIncrement() == 0) {
throw IllegalStateException("printer buffer full")
}
return "$orderId: slip printed"
}
fun main() = runBlocking {
val orderIds = listOf("O-3001", "O-3002", "O-3003")
val runner = RetryingTaskRunner(timeoutMs = 300)
val results = runner.runAll(orderIds, ::flakyPrint)
results.forEach { result ->
if (result.succeeded) println("OK ${result.value}")
else println("FAIL ${result.taskId}: ${result.error}")
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Calling a suspend function from plain, non-suspend code |
suspend functions can only run inside a coroutine or another suspend function -- it won't compile otherwise |
Start from runBlocking (an entry point) or mark the calling function suspend too |
Using Thread.sleep inside a coroutine instead of delay |
It blocks the real underlying thread, defeating the entire point of using coroutines on that dispatcher | Use delay (or wrap genuinely blocking calls in withContext(Dispatchers.IO), Section 5) |
Awaiting each async immediately after starting it (async { ... }.await(), one at a time) |
The work never overlaps -- this is sequential with extra ceremony, not parallel | Start every async first, collect the Deferreds, THEN await() each one (or awaitAll()) |
Using coroutineScope when one child's failure shouldn't affect the others |
A single failure cancels every sibling, even unrelated ones | Use supervisorScope, and await()/handle each child's own outcome |
| A loop with no suspension point, expecting cancellation to "just work" | Cancellation is cooperative -- nothing stops a tight loop with no delay/suspend call until it checks itself |
Check isActive (or call ensureActive()/yield()) inside the loop |
catch (e: Exception) around a cancellable block, without checking for CancellationException |
Swallows cancellation silently -- the coroutine "fails" instead of actually stopping | Catch CancellationException separately (or check e is CancellationException) and always rethrow it |
The same mistake via runCatching |
runCatching catches every Throwable, cancellation included |
result.onFailure { if (it is CancellationException) throw it; ... } |
Doing CPU-bound work on Dispatchers.IO, or blocking calls on Dispatchers.Default |
IO's large pool wastes threads on CPU work; Default's small pool starves if blocking calls tie its few threads up |
Match the dispatcher to the work: Default for computation, IO for genuinely blocking calls |
Quick recap
suspendfunctions pause without blocking a thread;delayis the suspend-world equivalent ofThread.sleep.runBlockingbridges ordinary code into coroutines;launchis fire-and-forget (Job);async/awaitgets a result back (Deferred<T>) and only pays for parallelism if everyasyncstarts before anyawait.coroutineScopeties children together (one failure cancels all);supervisorScopeisolates each child's failure instead.- Cancellation is cooperative: suspension points check automatically; loops without one need
isActive;finallystill runs;withTimeout/withTimeoutOrNullcancel a block on a deadline. Dispatchers.Defaultis for CPU work,Dispatchers.IOfor blocking calls,withContextswitches for one block; many coroutines genuinely share few real threads.try/catchworks normally aroundsuspendcalls; useCoroutineExceptionHandler+SupervisorJobfor uncaught failures inlaunch; always rethrowCancellationException, including out ofrunCatching.- A concurrent task runner is
supervisorScope+async+ a per-tasktry/catch, generic over the task's result type, with every wait expressed asdelay, neverThread.sleep.
Checklist
- I wrote a
suspendfunction and called it, and understand why it can't be called from plain code. - I timed the same three calls sequentially and with
async, and watched the parallel version come in at roughly the slowest call's time instead of the sum. - I made one failure cancel its siblings with
coroutineScope, then isolated it withsupervisorScope. - I cancelled a running coroutine with
cancelAndJoin()and watched itsfinallyblock run. - I used
withTimeout/withTimeoutOrNulland explained the difference between them. - I ran work on
Dispatchers.DefaultandDispatchers.IOand explained when to use each. - I hit the
runCatching-swallows-cancellation pitfall myself, then fixed it. - I built and ran the concurrent task runner, including one task that fails and one that times out, and confirmed the rest still succeed.