Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 14 / Topic 3 of 7

Structured concurrency and scopes

Structured concurrency means a coroutine's children are tied to its scope: the scope cannot finish until every child does, and a child can never outlive the block that started it (unlike a raw background thread, which can keep running after the function that started it returns). coroutineScope is the builder for this: it suspends until all its children finish, and if any child fails, it cancels every other child and rethrows.

suspend fun syncPartner(name: String, delayMs: Long, fail: Boolean = false): String {
    try {
        delay(delayMs)
        if (fail) throw IllegalStateException("$name API returned 503")
        return "$name synced"
    } catch (e: CancellationException) {
        println("  $name was cancelled")
        throw e                      // always rethrow CancellationException, never swallow it
    }
}
try {
    coroutineScope {
        launch { println("  " + syncPartner("Swiggy", 100)) }
        launch { syncPartner("Zomato", 200, fail = true) }
        launch { println("  " + syncPartner("Dunzo", 1000)) }
    }
} catch (e: IllegalStateException) {
    println("coroutineScope failed: ${e.message}")
}
--- coroutineScope: all children must finish; one failure cancels the rest
  Swiggy synced
  Dunzo was cancelled
coroutineScope failed: Zomato API returned 503

Swiggy (100ms) finishes before Zomato fails at 200ms; Dunzo (which needed 1000ms) is still waiting when Zomato fails, so coroutineScope cancels it -- its catch (e: CancellationException) runs, prints, and rethrows, and only then does the exception surface from coroutineScope itself.

Sometimes one failure should not take down its siblings -- supervisorScope gives each child its own fate: a failing child doesn't cancel the others, but you must await() (or otherwise observe) each one yourself to see whether it failed.

supervisorScope {
    val jobs = listOf(
        Triple("Swiggy", 100L, false),
        Triple("Zomato", 100L, true),
        Triple("Dunzo", 300L, false),
    ).map { (name, ms, fail) -> async { syncPartner(name, ms, fail) } }

    jobs.forEach { deferred ->
        try {
            println("  " + deferred.await())
        } catch (e: IllegalStateException) {
            println("  failed: ${e.message}")
        }
    }
}
--- supervisorScope: a failing child does not cancel its siblings
  Swiggy synced
  failed: Zomato API returned 503
  Dunzo synced

Dunzo still finishes successfully even though Zomato failed -- the whole point of supervisorScope. Use coroutineScope when the children are a single unit of work (all succeed or none do); use supervisorScope when they're independent and one failing shouldn't ruin the rest -- exactly the shape Section 7's task runner needs.

Full program: examples/03_structured_concurrency_and_scopes.kt.

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide