Structured concurrency and cancellation
Why it matters
- Prevents memory leaks by ensuring background tasks die with their owner.
- Avoids wasted CPU and battery by stopping unnecessary computations.
- Prevents 'zombie' tasks from updating UI or databases after a user leaves a screen.
- Crucial for passing senior interviews regarding error propagation and resource safety.
The simple explanation
- A restaurant kitchen manager (Parent Scope).
- Chefs (Child Coroutines) preparing different parts of a meal.
- If the manager cancels the order, every chef is told to stop, and each one stops at the next point where they check.
- If one chef drops a pan (fails), the kitchen's rules decide whether everyone stops or the others keep cooking.
Structured concurrency means every coroutine has a parent, and three rules follow from the Job hierarchy:
- Cancelling a parent cancels all of its children.
- A parent does not complete until all of its children have completed.
- A child that fails with an exception (other than
CancellationException) cancels its parent, which cancels the other children, unless the parent uses supervisor behaviour.
Every coroutine started with launch or async in a scope gets a Job that is a child of that scope's Job.
Regular Job vs SupervisorJob
| Event | Regular Job (coroutineScope) | SupervisorJob (supervisorScope, viewModelScope) |
|---|---|---|
| A child fails | The parent cancels the other children, then fails with the same exception | Only that child fails; the parent and the other children keep running |
| A child is cancelled | Only that child stops; the parent is not affected | Only that child stops; the parent is not affected |
| The parent is cancelled | All children are cancelled | All children are cancelled |
Supervisor behaviour applies only to direct children. A coroutineScope or plain launch nested inside a supervisor child still uses the regular rules for its own children.
Cooperative cancellation
Cancellation is not preemptive. Cancelling a Job only marks it as cancelled; the code notices at its next cancellable suspension point, where a CancellationException is thrown. All suspend functions in kotlinx.coroutines, such as delay, withContext, await and yield, check for cancellation. A loop that never suspends must check for itself with ensureActive(), isActive or yield(), or it keeps running and its parent cannot complete.
You can catch CancellationException to log or clean up, but rethrow it. If you swallow it, the Job stays cancelled while your code carries on as if nothing happened.
Try the simulator below. The parent coroutine uses coroutineScope (a regular Job) or supervisorScope (supervisor behaviour) around its three children. viewModelScope itself uses a SupervisorJob, which is why it stays active when the parent fails.
Switch the kind of scope around the children, then cancel or fail something.
- viewModelScopeactive
- launch { coroutineScope { … } }active
- child 1: load profileactive
- child 2: load feedactive
- child 3: load badgesactive
Everything is running. Try an action.
Notes
- Cancellation is cooperative; use
ensureActive()in long-running loops that do not suspend. - With a regular
Job, a child failure travels up to the parent and from there down to the siblings. - With a
SupervisorJob, a child failure does not travel up, so the child must handle its own error. - Cancelling a child never cancels its parent. Only real failures travel up.
CancellationExceptionsignals normal cancellation. It is never reported as a crash, and you should rethrow it when you catch it.finallyblocks run when a coroutine is cancelled. A cancellable suspend call insidefinallythrowsCancellationExceptionstraight away, so wrap suspend cleanup inwithContext(NonCancellable).job.cancel()only requests cancellation. UsecancelAndJoin()to wait until the coroutine has actually finished.- Do not pass
Job()orSupervisorJob()tolaunchorwithContext:launch(SupervisorJob())makes that Job the new coroutine's parent, so it is no longer a child of the scope and is not cancelled with it. viewModelScopeis cancelled when the ViewModel is cleared, andlifecycleScopewhen the lifecycle is destroyed.runCatchingcatchesCancellationExceptiontoo, so code keeps running after cancellation.
Code example
The same four situations as the simulator, in runnable code: a failure under coroutineScope, a failure under supervisorScope, cancelling a parent, and stopping a CPU loop.
import kotlinx.coroutines.*
suspend fun child(name: String, ms: Long, fail: Boolean = false) {
try {
delay(ms)
if (fail) throw IllegalStateException(name + " failed")
println(" " + name + " done")
} catch (e: CancellationException) {
println(" " + name + " cancelled")
throw e // always rethrow
}
}
fun main() = runBlocking {
println("1. coroutineScope, child 2 fails")
try {
coroutineScope {
launch { child("child 1", 200) }
launch { child("child 2", 100, fail = true) }
launch { child("child 3", 300) }
}
} catch (e: IllegalStateException) {
println(" caught: " + e.message)
}
println("2. supervisorScope, child 2 fails")
val handler = CoroutineExceptionHandler { _, e -> println(" handler: " + e.message) }
supervisorScope {
launch { child("child 1", 200) }
launch(handler) { child("child 2", 100, fail = true) }
launch { child("child 3", 300) }
}
println("3. cancel the parent")
val parent = launch {
launch { child("child 1", 200) }
launch { child("child 2", 300) }
}
delay(100)
parent.cancelAndJoin()
println(" parent cancelled: " + parent.isCancelled)
println("4. CPU loop with ensureActive")
val loop = launch(Dispatchers.Default) {
var count = 0L
while (true) {
ensureActive() // without this line, cancelAndJoin would wait forever
count++
}
}
delay(50)
loop.cancelAndJoin()
println(" loop stopped")
}Expected output:
1. coroutineScope, child 2 fails
child 1 cancelled
child 3 cancelled
caught: child 2 failed
2. supervisorScope, child 2 fails
handler: child 2 failed
child 1 done
child 3 done
3. cancel the parent
child 1 cancelled
child 2 cancelled
parent cancelled: true
4. CPU loop with ensureActive
loop stopped
- In case 1,
coroutineScopewaits for the cancelled siblings to finish and then rethrows the original exception, so onetry/catcharound it handles the whole group. - In case 2, nobody above handles child 2's failure, so it goes to the
CoroutineExceptionHandleron that child. Without one, the exception would reach the thread's uncaught exception handler, which crashes an Android app. - In case 3, cancelling a parent cancels its children, and
cancelAndJoinwaits until they have finished. - In case 4, the loop never suspends, so only
ensureActive()lets it notice the cancellation.
In production
- Battery reports and server load went up after a release with a live map screen.
- The backend kept receiving location updates from map sessions the user had closed long ago.
- Cause: the screen started its update loop with
GlobalScope.launch { while (true) { send(location()); delay(10_000) } }, so nothing cancelled it when the screen went away.
- Moved the loop into the screen's ViewModel with
viewModelScope.launch, so it is cancelled when the ViewModel is cleared. - Changed the loop condition to
while (isActive)and kept thedelay, which is also a cancellation point. - Added a lint check that flags new uses of
GlobalScope.
- On a search screen, typing quickly sometimes showed "Something went wrong" over correct results.
- Each new query called
searchJob?.cancel()and launched a new search. The old search hadcatch (e: Exception) { _state.value = UiState.Error }. - The cancelled search's
CancellationExceptionlanded in that catch, which wrote an error state after the new search had started.
- Added
catch (e: CancellationException) { throw e }before the generic catch, and narrowed the generic catch toIOExceptionandHttpException. - Replaced the manual job handling with
flatMapLatestover a queryStateFlow, so the old search is cancelled for you. - Added a test that sends two queries quickly and checks that no error state appears.
Common mistakes
- Using GlobalScope. Its coroutines are not tied to any lifecycle, so they keep running and keep their captured objects reachable after the screen is gone.
- Swallowing CancellationException. The Job stays cancelled, but your code keeps running: it writes state, reports false errors, or loops.
- Ignoring cooperative cancellation. A
while (true)loop that never suspends and never checksisActiveor callsensureActive()does not stop when its scope is cancelled. - Using a regular Job for independent tasks. One minor failure, like an image failing to load, cancels every other task in that scope. Use
supervisorScopeand handle each child's error. - Passing a Job to launch.
scope.launch(SupervisorJob()) { ... }does not make the children supervised. It replaces the parent, so the coroutine escapes the scope's cancellation. - Calling a suspend function in finally without NonCancellable. After cancellation, a cancellable suspend call in
finally(such asdelayor a suspend DAO call) throwsCancellationExceptionstraight away. Wrap the cleanup inwithContext(NonCancellable).
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is structured concurrency?”
“What is the difference between Job and SupervisorJob?”
“How do you make a long-running loop cancellable?”
“What happens if you catch an exception in a coroutine?”
Quiz
Which of these is a way to make a non-suspending loop cooperative with cancellation?
If a child coroutine fails with an exception in a standard CoroutineScope, what happens to the parent?
A cancelled coroutine must close a resource with a suspend call in its finally block. What do you use?
An app-level class needs its own long-lived scope for independent background jobs. Which is best?
0 of 4 answered
Mini task
Task: The Cooperative Loop
Goal: Create a function that simulates a heavy computation loop that respects cancellation.
-
Create a
suspendfunction calledheavyComputationthat takes anIntparameteriterations. -
Inside the function, use a
forloop from 1 toiterations. In each step, do CPU work with no suspend call, for example summing the numbers from 1 to 1,000,000 into a running total that you print at the end. -
Launch it with
iterations = 5_000fromrunBlockingusinglaunch(Dispatchers.Default), waitdelay(300), then callcancelAndJoin(). Notice thatcancelAndJoin()waits until the whole loop is done: nothing in the loop checks for cancellation. -
Add
currentCoroutineContext().ensureActive()at the start of each step. -
Print "Loop finished" after the loop. Wrap the loop in
try/catch (e: CancellationException), print "Loop interrupted" in the catch, and rethrowe.
Done Condition: After step 4, the program prints "Loop interrupted" about 300 ms after starting and never prints "Loop finished". Remove the ensureActive() call and the program runs for several seconds until the loop ends and prints "Loop finished".