The Analogy: The Diver and the Surface Tender
A commercial diver works on the seabed while a surface tender sits in the boat above, holding the lifeline that carries the diver's air, communications, and signals. The tender cannot reach down and switch the diver off. All they can do is send a command down the line and wait for the diver to act on it. The diver is doing the real work below; the tender governs the dive from above, but only through cooperation.
When the supervisor decides the dive must end, the tender tugs the line to signal a recall. But the diver, hands deep inside a valve assembly, cannot vanish on the instant. They respond at the next natural pause -- when a bolt is finished, when a tool is clear of the work -- because stopping mid-turn could damage the equipment or the diver. A diver who is checking the line regularly comes up promptly. A diver so absorbed that they never glance at the line cannot be recalled at all until they next pay attention, and the whole operation waits on them.
There is a second way a dive ends: the dive tables impose a hard limit on bottom time, and when that clock runs out the recall is automatic, no matter what the diver is doing. Whether the recall comes from the supervisor's decision or the expiry of the clock, the ending is never instantaneous. The diver still has to secure their tools and stage a controlled ascent with decompression stops. Stopping is itself a process that takes time and care, and it has to happen even when -- especially when -- the dive is being cut short.
The failures cluster exactly at this boundary. A diver who ignores every signal stalls the whole operation, because cooperation is the only control the surface has. A diver who panics and bolts straight to the surface skips the decompression and gets the bends -- the abort was handled, but the cleanup was skipped, and skipping cleanup is its own disaster. And there is a subtler trap: if the surface cuts the diver's support the very instant it calls the abort, it removes the one thing the diver needs to secure their gear and ascend safely. A safe recall has to keep supporting the diver through the ascent, not abandon them at the moment the order is given.
Syntax or Core Structure
Cancellation in Kotlin is cooperative. Calling cancel on a Job does not forcibly stop the coroutine; it requests a stop, and the coroutine notices at its next cancellable suspension point -- a delay, a yield, any suspending call -- where a CancellationException is thrown. cancelAndJoin requests the stop and then waits for the coroutine to finish winding down.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
var tick = 0
while (true) {
delay(50L) // a cancellable suspension point
tick++
println("tick " + tick)
}
}
delay(175L) // let three ticks happen
println("recall")
job.cancelAndJoin()
println("job stopped")
}
Output:
tick 1
tick 2
tick 3
recall
job stopped
The launched coroutine ticks every 50 milliseconds, so it prints "tick 1" at 50, "tick 2" at 100, and "tick 3" at 150. Meanwhile main waits 175 milliseconds, wakes, and prints "recall". At that moment the coroutine is suspended inside its delay -- the one that started at 150 and would have fired "tick 4" at 200. cancelAndJoin requests cancellation, and because delay is a cancellable suspension point, it throws CancellationException there instead of returning, so "tick 4" never prints. The 25-millisecond margin on either side of the recall keeps the count fixed at three. join then waits for the coroutine to actually finish, after which "job stopped" prints. The tug on the line was noticed at the next pause, exactly as the diver responds between turns of the wrench.
Technical Depth: Cooperation, Timeouts, and Winding Down
The tools of cancellation
Cancellation works only if the coroutine cooperates. These are the pieces that make it cooperate, and each corresponds to the diver watching the line.
| Tool | What it does |
|---|---|
| cancel | requests cancellation of a Job, returns at once |
| cancelAndJoin | requests cancellation, then waits for wind-down |
| isActive | true until the coroutine is cancelled; check it in loops |
| ensureActive | throws CancellationException if already cancelled |
| yield | gives up the thread and is a cancellation point |
Suspending functions from the library, such as delay, are already cancellable: they throw CancellationException when the coroutine is cancelled. The problem case is a tight computational loop that never suspends and never checks -- the diver who never looks at the line. Such a loop must add a check with isActive, ensureActive, or yield to become cancellable.
import kotlinx.coroutines.*
fun main() = runBlocking {
val result = coroutineScope {
var sum = 0
for (n in 1..5) {
ensureActive() // cooperative check a CPU loop must add
sum += n
}
"isActive stayed true, sum=" + sum
}
println(result)
}
Output:
isActive stayed true, sum=15
The loop calls ensureActive on every iteration, which throws only if the coroutine has been cancelled. Here nothing cancels it, so every check passes, all five numbers are added, and the sum is 15. The value of the pattern is what would happen under cancellation: the very next ensureActive would throw and stop the loop promptly, instead of grinding on for the full computation. A CPU-bound loop without such a check is the diver who never glances up.
Timeouts: the dive-table clock
A timeout is the hard limit on bottom time. withTimeout runs a block and cancels it if it overruns, throwing TimeoutCancellationException. withTimeoutOrNull does the same but returns null on overrun instead of throwing, which is often easier to handle.
| Function | On overrun | Returns on success |
|---|---|---|
| withTimeout | throws TimeoutCancellationException | the block's result |
| withTimeoutOrNull | returns null | the block's result |
import kotlinx.coroutines.*
fun main() = runBlocking {
val slow = withTimeoutOrNull(100L) {
delay(200L) // overruns the 100ms budget
"slow done"
}
val fast = withTimeoutOrNull(100L) {
delay(30L) // finishes within budget
"fast done"
}
println("slow result: " + slow)
println("fast result: " + fast)
}
Output:
slow result: null
fast result: fast done
The first block needs 200 milliseconds but is given only 100, so its delay is cancelled when the budget expires and withTimeoutOrNull yields null. The second block finishes its 30-millisecond wait well inside the 100-millisecond budget, so it returns "fast done" normally. The clock ran out on the first dive and recalled it; the second surfaced in time on its own.
Cancellation flows down the tree
Structured concurrency means cancelling a parent cancels its children, and join waits for the whole subtree to wind down. You never have to chase children individually; the recall propagates.
import kotlinx.coroutines.*
fun main() = runBlocking {
val parent = launch {
launch {
try {
delay(1000L)
} finally {
println("child stopped too")
}
}
println("child launched")
delay(1000L)
}
delay(50L)
parent.cancelAndJoin()
println("parent cancelled")
}
Output:
child launched
child stopped too
parent cancelled
The parent launches a child that waits a full second inside try/finally, prints "child launched", then waits a second itself. After 50 milliseconds main cancels the parent. Cancelling the parent cancels the child as well, so the child's delay throws and its finally prints "child stopped too". Because cancelAndJoin waits for the entire subtree, that cleanup finishes before "parent cancelled" prints. One recall stopped both coroutines, and nothing was left running.
Real World Example: Cancelling a Stream with Cleanup
This program opens a stream, reads chunks on a timer, and uses try/finally to flush and close the stream when the work ends. The flush is a suspending call, because flushing a real buffer to disk or network takes a moment. The program cancels the stream partway through, and the interesting question is whether the flush actually completes.
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
try {
println("stream opened")
var chunk = 0
while (true) {
delay(50L)
chunk++
println("chunk " + chunk)
}
} finally {
println("entering cleanup")
delay(30L) // suspending flush, no NonCancellable guard
println("flush complete")
}
}
delay(125L)
println("recall")
job.cancelAndJoin()
println("stream cancelled")
}
Output:
stream opened
chunk 1
chunk 2
recall
entering cleanup
stream cancelled
The stream opens and reads chunks every 50 milliseconds: "chunk 1" at 50 and "chunk 2" at 100. main waits 125 milliseconds, so it wakes between the second and third chunk -- with a 25-millisecond margin on each side -- and prints "recall". At that instant the coroutine is suspended in the delay that would have produced "chunk 3" at 150.
cancelAndJoin requests cancellation, and the suspended delay throws CancellationException. That exception unwinds through the try, and the finally block runs -- which is why "entering cleanup" prints. try/finally fires on cancellation just as it does on a normal exit, so the intent to clean up is honoured.
But then the flush stalls. The line "flush complete" never prints, even though the finally block clearly reaches it. The stream is left un-flushed, and "stream cancelled" prints instead as the coroutine finishes cancelling.
The genuine design flaw is that the flush is a suspending call inside a finally block, made while the coroutine is already being cancelled. A coroutine that is cancelling throws CancellationException at the very next suspension point, so the delay in the flush throws immediately and "flush complete" is skipped. This is the diver whose support was cut at the instant of the abort, unable to finish the safe ascent. The fix is to wrap suspending cleanup in withContext(NonCancellable), which keeps that block runnable through cancellation so the flush finishes and the buffer is not lost. Non-suspending cleanup such as the "entering cleanup" print is unaffected; it is specifically suspending work in finally that needs the NonCancellable guard.
Common Mistakes
- Assuming
cancelstops a coroutine instantly. It only requests cancellation. The coroutine stops at its next cancellable suspension point or cooperative check. A coroutine that never suspends or checks keeps running regardless.
- Writing a CPU-bound loop with no cancellation check. A tight computational loop never hits a suspension point, so cancellation is invisible to it. Add
isActive,ensureActive, oryieldso the loop can be recalled.
- Swallowing
CancellationException. Catching it in a broadcatchand not rethrowing tells the runtime the coroutine is fine, breaking cancellation. Let it propagate, or rethrow it after any local handling.
- Suspending in
finallywithoutNonCancellable. A cancelling coroutine throws at the next suspension point, so suspending cleanup infinallyis skipped. Wrap it inwithContext(NonCancellable)so the cleanup completes.
- Using
withTimeoutand not handling the throw.withTimeoutthrowsTimeoutCancellationExceptionon overrun. If you do not catch it or usewithTimeoutOrNull, it propagates and can cancel more than you intended.
- Catching
Exceptionand accidentally catching cancellation.CancellationExceptionis anException, so a broadcatch (e: Exception)swallows it too. Rethrow it explicitly, or catch narrower types.
- Cancelling the wrong
Job. Cancelling a parent cancels all its children, sometimes more than you meant. Cancel the specificJobwhose work you want to stop, and understand the scope you are cancelling.
- Forgetting that a timeout cancels its block. When
withTimeoutfires, the block is cancelled at its next suspension point, so partial work inside may be abandoned. Design the block so an interrupted run leaves no half-written state.
- Relying on
delayfor precise timing.delayguarantees at least the given time, not exact timing. Deterministic ordering comes from clear margins between events, not from delays being exact to the millisecond.
Best Practices
- Treat cancellation as cooperative: make sure every long-running coroutine reaches a suspension point or a cooperative check regularly.
- Add
ensureActive,isActive, oryieldto CPU-bound loops so they can be recalled instead of grinding to completion.
- Always let
CancellationExceptionpropagate; if you catch broadly, rethrow it so cancellation still works.
- Wrap suspending cleanup in
withContext(NonCancellable)insidefinally, so flushing and closing complete even during cancellation.
- Prefer
withTimeoutOrNullwhen a timeout is an expected outcome you want to branch on, andwithTimeoutwhen overrun is a real error.
- Use
try/finallyto release resources, remembering it runs on cancellation as well as normal exit.
- Cancel the narrowest
Jobthat covers the work you want to stop, and rely on structured concurrency to cancel its children.
- Design timed blocks so that an interrupted run leaves no partially written state behind.
Practice Exercises
- Write a coroutine that prints a tick every 40 milliseconds, cancel it after 150 milliseconds with
cancelAndJoin, and predict exactly how many ticks print before the recall.
- Write a CPU-style loop that sums a large range with no suspension point, launch it, and try to cancel it; observe that it ignores the cancellation. Then add
ensureActiveto the loop and show it now stops.
- Use
withTimeoutOrNullwith a 100-millisecond budget around a block that delays 60 milliseconds, and another that delays 140 milliseconds. Predict which returns a value and which returns null.
- Take the stream in this lesson and wrap the suspending flush in
withContext(NonCancellable). Show that "flush complete" now prints during cancellation, and explain in a comment why the guard was needed.