Structured concurrency and cancellation

You will understand how the Coroutine Job hierarchy manages the lifecycle of concurrent tasks and how to ensure they stop correctly when no longer needed. About 25 minutes.

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

EventRegular Job (coroutineScope)SupervisorJob (supervisorScope, viewModelScope)
A child failsThe parent cancels the other children, then fails with the same exceptionOnly that child fails; the parent and the other children keep running
A child is cancelledOnly that child stops; the parent is not affectedOnly that child stops; the parent is not affected
The parent is cancelledAll children are cancelledAll 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.

Try it: who gets cancelled?

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.

Cancel the parent, stop every child
Cancel the parent, stop every child Calling job.cancel() cancels the parent job, the parent cancels children A, B and C, and each child gets a CancellationException at its next suspension point. CANCELS job.cancel() Parent job launch { … } Child A launch Child B launch Child C async CancellationException at each child's next suspension point
Cancellation flows down the job tree; each child stops at its next suspension point with a CancellationException.

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.
  • CancellationException signals normal cancellation. It is never reported as a crash, and you should rethrow it when you catch it.
  • finally blocks run when a coroutine is cancelled. A cancellable suspend call inside finally throws CancellationException straight away, so wrap suspend cleanup in withContext(NonCancellable).
  • job.cancel() only requests cancellation. Use cancelAndJoin() to wait until the coroutine has actually finished.
  • Do not pass Job() or SupervisorJob() to launch or withContext: 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.
  • viewModelScope is cancelled when the ViewModel is cleared, and lifecycleScope when the lifecycle is destroyed.
  • runCatching catches CancellationException too, 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, coroutineScope waits for the cancelled siblings to finish and then rethrows the original exception, so one try / catch around it handles the whole group.
  • In case 2, nobody above handles child 2's failure, so it goes to the CoroutineExceptionHandler on 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 cancelAndJoin waits until they have finished.
  • In case 4, the loop never suspends, so only ensureActive() lets it notice the cancellation.

In production

The Ghost Analytics Tracker
  • 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.
The fix
  • 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 the delay, which is also a cancellation point.
  • Added a lint check that flags new uses of GlobalScope.
Error message after a new search
  • 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 had catch (e: Exception) { _state.value = UiState.Error }.
  • The cancelled search's CancellationException landed in that catch, which wrote an error state after the new search had started.
The fix
  • Added catch (e: CancellationException) { throw e } before the generic catch, and narrowed the generic catch to IOException and HttpException.
  • Replaced the manual job handling with flatMapLatest over a query StateFlow, 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 checks isActive or calls ensureActive() 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 supervisorScope and 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 as delay or a suspend DAO call) throws CancellationException straight away. Wrap the cleanup in withContext(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.

  1. Create a suspend function called heavyComputation that takes an Int parameter iterations.

  2. Inside the function, use a for loop from 1 to iterations. 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.

  3. Launch it with iterations = 5_000 from runBlocking using launch(Dispatchers.Default), wait delay(300), then call cancelAndJoin(). Notice that cancelAndJoin() waits until the whole loop is done: nothing in the loop checks for cancellation.

  4. Add currentCoroutineContext().ensureActive() at the start of each step.

  5. Print "Loop finished" after the loop. Wrap the loop in try / catch (e: CancellationException), print "Loop interrupted" in the catch, and rethrow e.

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".

Next: Exception handling in coroutines