Skip to content
Tutorials Center
My learning

Topics

Lesson 96 of 134 ยท Coroutines

Structured Concurrency

Learn structured concurrency in Kotlin coroutines - parent-child jobs, scopes, how a parent waits for children, cancellation and failure propagation, coroutineScope vs supervisorScope, and why GlobalScope is a trap.

Threads have a famous problem: you start one and then lose track of it. It may outlive the function that created it, fail without anyone noticing, or keep running after its result is no longer needed. This is called a leak, and it is the source of countless bugs in concurrent programs. Kotlin's answer is structured concurrency: every coroutine lives inside a scope, a scope knows all its coroutines, and the scope cannot finish until they all have.

The rule is easy to say: a coroutine's lifetime is bounded by its parent's. From it follow three guarantees you can rely on: nothing is left running after a scope ends, an error in a child is not lost, and cancelling a scope cancels everything inside it. This lesson shows each guarantee in code. It builds on the builders and is followed by cancellation and timeouts.

Parents wait for children

Every launch or async inside a scope creates a child of that scope's Job. A parent coroutine does not complete until all its children have completed, even if its own code is finished.

Kotlin The parent waits for its children

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The body of coroutineScope is finished after the third print, but the function does not return until both children are done. Everything started inside is finished when coroutineScope returns. This is the property that makes suspend functions safe to call: a function that uses coroutineScope can never leave a stray coroutine behind.

Seeing the hierarchy

Every coroutine has a Job in its context, and the jobs form a tree. You can inspect it with coroutineContext[Job] and its children sequence:

Kotlin The Job tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first count is 3 because runBlocking owns three children at that moment. The outer coroutine in turn has two children of its own, and it is only "completed" when they are too. The tree is the data structure that makes the rest of this lesson work: cancellation travels down the tree, failures travel up.

Cancellation goes down

When you cancel a coroutine, all its children are cancelled too. Cancel a whole scope, and all its coroutines stop. Cancellation is cooperative: a suspended coroutine stops at its next suspension point (the details are in cancellation).

Kotlin Cancelling a parent cancels the children

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both children were cancelled even though we cancelled only the parent. The finally block ran, which is how coroutines release resources on cancellation. Rethrow CancellationException when you catch it, otherwise the coroutine pretends it was not cancelled.

Failure goes up

When a child fails with an exception, the failure goes to its parent. By default the parent is then cancelled, and so are all the siblings. The whole tree stops, and the exception comes out at the top. This is fail fast: a bug cannot hide in a corner.

Kotlin A failing child cancels its siblings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The failing child cancelled the slow sibling (its finally ran), the scope rethrew the exception, and the try/catch around work() caught it. This is the reason structured concurrency makes error handling feel ordinary: the exception reaches the caller of the function that created the scope.

A try/catch around a launch call does not catch the child's exception, because the child runs later and elsewhere. Put the try/catch inside the coroutine, or around the whole coroutineScope. Details are in exceptions in coroutines.

supervisorScope: independent children

Sometimes children should fail independently: a dashboard with five widgets should not go dark because one widget's request failed. supervisorScope changes the failure rule: a failing child does not cancel its siblings or the scope. The scope's own body still fails if it throws.

With async, you handle the failure where you await:

Kotlin supervisorScope keeps siblings alive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

All three results are reported, two successes and one failure, because the failure of news did not touch the others. Compare with coroutineScope, where the first failure would have cancelled everything. Choose coroutineScope when the parts are all needed for one result, and supervisorScope when they are independent.

Your own scopes

The builders launch and async are extension functions on CoroutineScope. Inside runBlocking or coroutineScope, you already have a scope. In classes (a screen, a service) you often create your own scope and cancel it when the object is no longer needed. CoroutineScope(context) takes a context; it should contain a Job (a SupervisorJob if children are independent) so that it can be cancelled.

Kotlin A class that owns a scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Closing the scope cancels both downloads, and cancelAndJoin waits until their finally blocks have run. We sorted the log because two coroutines on a multi-threaded dispatcher may log in either order.

GlobalScope: the way back to leaks

GlobalScope is a scope that lives as long as the whole program and has no parent. A coroutine launched in it is not waited for, not cancelled with anything and not connected to any error handling. That is exactly the unstructured situation structured concurrency was invented to avoid, which is why using it produces a compiler warning about a delicate API. The following example shows the danger: the program ends before the global coroutine finishes.

Kotlin GlobalScope work is abandoned

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only main is done appears. If you ever believe you need GlobalScope, you probably need a scope owned by your class or by the application, which you create, pass around and cancel.

Rules of thumb

  • Start coroutines only inside a scope you own or inherit; never leave them dangling.
  • Write concurrent suspend functions with coroutineScope { ... }; the caller needs no scope.
  • Use supervisorScope when children are independent, and handle each child's error.
  • Rethrow CancellationException; use finally for cleanup.
  • Cancel scopes you create, usually in a close() or onCleared() method.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a parent coroutine do when its own code has finished but children are still running?

    A parent completes only after all of its children have completed.
  2. 2. In a coroutineScope, one child throws an exception. What happens to its siblings?

    Failures go up to the parent, which cancels the other children and then fails itself.
  3. 3. When is supervisorScope the better choice?

    supervisorScope does not propagate a child's failure to its siblings.
  4. 4. Why is GlobalScope.launch discouraged?

    GlobalScope breaks structured concurrency and can leak work.
  5. 5. What should you do when you catch a CancellationException?

    Swallowing it makes the coroutine look as if it had not been cancelled.

Summary

  • Structured concurrency: every coroutine runs in a scope, and a scope waits for all its children.
  • Jobs form a tree; cancellation travels down to children, failures travel up to parents.
  • coroutineScope cancels all children if one fails; supervisorScope lets children fail independently.
  • Use your own CoroutineScope(SupervisorJob() + ...) for objects with a lifecycle, and cancel it when done.
  • Avoid GlobalScope; it is a leak waiting to happen.
  • Use finally for cleanup and rethrow CancellationException.

Next: Cancellation and Timeouts