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

Part 14 / Topic 4 of 7

Cancellation is cooperative

Cancelling a coroutine doesn't forcibly kill it the way Thread.interrupt() tries to -- it sets a flag and relies on the coroutine checking for it. A suspension point (anywhere a suspend function like delay is called) checks automatically and throws CancellationException if cancelled; code with no suspension points has to check isActive itself, or it never notices.

val thirdPoll = CompletableDeferred<Unit>()
val job = launch {
    try {
        repeat(10) { i ->
            println("polling order status feed #$i")
            if (i == 2) thirdPoll.complete(Unit)
            delay(100)                     // a suspension point: cancellation is checked here
        }
    } finally {
        println("closing feed connection")  // finally runs even when the coroutine is cancelled
    }
}
thirdPoll.await()
job.cancelAndJoin()
println("job cancelled: ${job.isCancelled}")

withTimeout/withTimeoutOrNull cancel a block automatically once a deadline passes -- withTimeoutOrNull returns null instead of throwing, withTimeout throws TimeoutCancellationException (a subtype of CancellationException):

val eta = withTimeoutOrNull(200) { delay(500); "ETA from slow partner" }
println("withTimeoutOrNull -> $eta")

try {
    withTimeout(200) { delay(500) }
} catch (e: TimeoutCancellationException) {
    println("withTimeout threw TimeoutCancellationException")
}

val busy = launch(Dispatchers.Default) {
    var n = 0L
    while (isActive) n++            // no suspension point -- must check isActive itself
}
delay(50)
busy.cancelAndJoin()
println("busy loop stopped: ${busy.isCancelled}")
polling order status feed #0
polling order status feed #1
polling order status feed #2
closing feed connection
job cancelled: true
withTimeoutOrNull -> null
withTimeout threw TimeoutCancellationException
busy loop stopped: true

finally runs on cancellation exactly like it would on any other exception -- "closing feed connection" prints before job.cancelAndJoin() returns, which is why cleanup code (closing a connection, releasing a lock) belongs in finally, not after the loop.

Full program: examples/04_cancellation.kt.

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

Search the guide