Kotlin › Practice

Structured concurrency and CancellationException in Kotlin

Why catch(Exception) and runCatching break coroutine cancellation, plus benchmarks for coroutineScope, supervisorScope, withTimeout, and GlobalScope.

Structured concurrency and CancellationException in Kotlin

A notice-sync coroutine worker kept logging after Spring shut down, and a cancelled polling loop pinned a full CPU core. Both bugs traced back to code that caught CancellationException like a normal runtime error. Here are five cancellation traps reproduced in tests, measured locally, and fixed cleanly.

Tested with Kotlin 2.1.0, kotlinx.coroutines 1.10.1, Spring Boot 3.4.2, Java 21, and Gradle 8.12.1. Because Spring Boot 3.4.2’s BOM pins kotlinx.coroutines to 1.8.1, I overrode it with extra["kotlin-coroutines.version"] = "1.10.1". All numbers come from running ./gradlew test three times on a local PC (12 cores, 32GB RAM, Windows with Docker Desktop/WSL2).

The problem

Our club service runs a background coroutine worker that polls an external endpoint for new notices. To keep transient network errors from killing the loop, I wrapped the polling call in try { ... } catch (e: Exception). During deployments, however, “polling failed” logs kept printing after the Spring context closed, and in tests job.join() never returned after job.cancel().

In my earlier post comparing Kotlin Coroutines and Java Virtual Threads, I noted that coroutineScope cancels sibling work when a child fails or times out. That guarantee holds only if the cancellation signal isn’t swallowed along the way. This post covers the exact places where that assumption breaks.

Root cause

Coroutine cancellation is cooperative. Calling job.cancel() only flips the Job into the Cancelling state. The coroutine doesn’t actually stop until it hits a suspension point (delay, await, yield, and similar) that throws CancellationException and unwinds the call stack. Because CancellationException extends IllegalStateException, a broad catch (e: Exception) catches it immediately.

What happens next is worse than a missed stop. Because the Job is already cancelled, the next loop iteration calls delay(), which throws CancellationException immediately without suspending. The loop spins through delay → exception allocation → catch as fast as the CPU allows, and join() hangs forever because the child never terminates.

flowchart TD
    A["job.cancel() called"] --> B["Job enters Cancelling state"]
    B --> C["Next delay() throws CancellationException"]
    C --> D{"catch (e: Exception)"}
    D -->|"Swallowed"| E["Loop re-enters and throws immediately"]
    E --> C
    D -->|"Rethrown"| F["Stack unwinds to Cancelled"]

withTimeout works the same way. When the deadline expires, it throws TimeoutCancellationException, which is also a subclass of CancellationException. Parent coroutines treat it as normal cancellation rather than failure, which can silently hide timeouts inside top-level launch blocks.

Reproduction and measurements

To measure the damage, I ran a loop polling every 20ms for 200ms, cancelled the job, and waited up to 1 second for job.join().

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/test/kotlin/com/example/club/worker/CancellationSwallowTest.kt (excerpt)
val job: Job = scope.launch {
    while (!stopFlag.get()) {
        try {
            pollOnce(polls) // delay(20) then increment counter
        } catch (e: Exception) { // Catches CancellationException too
            failures.incrementAndGet()
        }
    }
}
delay(200)
job.cancel()
val joined = withTimeoutOrNull(1_000) { job.join(); true } ?: false
1
2
3
4
5
[RESULT] swallow: pollsBeforeCancel=6, joined=false, waitedMs=1007, swallowedAfterCancel=566187, pollsAfterCancel=1, isActive=false, isCancelled=true
[RESULT] ensureActive: cancelAndJoinUs=755, swallowed=0
[LOG] failure type=JobCancellationException
[RESULT] runCatching: saved=[default notice], jobCancelled=true
[RESULT] afterClose(1s): global +16 ticks, scoped +0 ticks, ctx.isActive=false

Across three test runs, the five failure modes behaved as follows:

ScenarioMeasured result (3 runs)
catch (e: Exception) then canceljoin() timed out after 1s; catch ran 450k–570k times
ensureActive() inside catchcancelAndJoin() finished in 0.76–0.84ms, 0 swallowed
runCatching + getOrElseCaught JobCancellationException and saved the fallback value
GlobalScope.launch workerKept firing 16 more ticks in the 1s after context shutdown
Bean-owned scope + @PreDestroy cancel0 ticks after context shutdown

Notice that isActive=false and isCancelled=true didn’t stop execution on their own. Flipping the job state and stopping user code are two separate things. Explicitly catching and rethrowing CancellationException also finished with zero swallowed exceptions; I left its 18.8–20.4ms timing out of the table because it ran first and included cold initialization overhead.

Next, I tested failure propagation and timeouts using one child that fails at 100ms alongside two 300ms sibling coroutines.

ConstructDuration (3 runs)Behavior
coroutineScope + launch105–118msBoth siblings cancelled at 104–117ms; exception propagated to caller
supervisorScope + launch303–305msBoth siblings completed; failure went to CoroutineExceptionHandler
supervisorScope + async303–318msReturned [notice-ok, fallback(profile failed)]
withTimeout(100)-Threw TimeoutCancellationException; not reported to handler in top-level launch
withTimeoutOrNull(100)-Returned null
xychart-beta
    title "Return time of Thread.sleep(500) inside withTimeoutOrNull(100) (ms)"
    x-axis ["withContext(IO)", "runInterruptible(IO)"]
    y-axis "ms" 0 --> 600
    bar [516, 107]

That last result caught me off guard. Even inside withTimeoutOrNull(100), a blocking Thread.sleep(500) on withContext(Dispatchers.IO) had no suspension point and didn’t return null until 515–517ms later. Wrapping the blocking call in runInterruptible(Dispatchers.IO) translated coroutine cancellation into a thread interrupt and returned in 106–108ms.

Choosing the right scope and timeout

RequirementChoiceReason
Parallel calls where one failure invalidates the whole responsecoroutineScope + asyncCancels siblings immediately and propagates the error
Independent tasks where partial failure is acceptablesupervisorScope + per-child error handlingIsolates failure from sibling coroutines
Treat a timeout as a missing valuewithTimeoutOrNullBranches on null without exception flow
Surface a timeout to callers as an errorwithTimeout mapped to a domain exceptionPrevents silent drops in top-level launch
Apply a timeout to blocking I/OrunInterruptibleInterrupts the underlying thread instead of waiting

Knowing when not to use each construct prevents subtle outages. supervisorScope isolates failures—it doesn’t handle them. If a launch child throws without a CoroutineExceptionHandler, the default handler just prints a stack trace. Don’t reach for supervisorScope when you’re building a single response that requires every child result; coroutineScope is the right tool there. And skip GlobalScope even for application-lifetime workers: without an owned scope handle, there is nothing to cancel on shutdown, so the coroutine outlives the Spring context just like in the benchmark above.

The fix

When you want Kotlin’s Result API around suspending code, define a helper that rethrows CancellationException before wrapping other exceptions.

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/main/kotlin/com/example/club/support/RunSuspendCatching.kt
package com.example.club.support

import kotlin.coroutines.cancellation.CancellationException

suspend inline fun <T> runSuspendCatching(block: () -> T): Result<T> =
    try {
        Result.success(block())
    } catch (e: CancellationException) {
        throw e
    } catch (e: Exception) {
        Result.failure(e)
    }

For background workers in Spring Boot, bind a CoroutineScope to the bean and cancel it in @PreDestroy. Calling ensureActive() at the top of catch (e: Exception) guarantees the loop exits immediately on cancellation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// src/main/kotlin/com/example/club/worker/ScopedNoticeSync.kt
package com.example.club.worker

import jakarta.annotation.PreDestroy
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Component

@Component
class ScopedNoticeSync(private val noticeClient: NoticeClient) {
    private val log = LoggerFactory.getLogger(javaClass)
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default + CoroutineName("notice-sync"))

    @EventListener(ApplicationReadyEvent::class)
    fun start() {
        scope.launch {
            while (isActive) {
                try {
                    noticeClient.sync()
                } catch (e: Exception) {
                    ensureActive() // Exit the loop immediately if cancelled
                    log.warn("Notice sync failed; retrying on next interval", e)
                }
                delay(60_000)
            }
        }
    }

    @PreDestroy
    fun stop() = scope.cancel("application context closed")
}

interface NoticeClient {
    suspend fun sync()
}
1
2
3
4
5
6
7
8
// build.gradle.kts (excerpt)
extra["kotlin-coroutines.version"] = "1.10.1"

dependencies {
    implementation("org.springframework.boot:spring-boot-starter")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}
1
2
3
4
# src/main/resources/application.yml
spring:
  lifecycle:
    timeout-per-shutdown-phase: 10s

Watch out for two testing and cleanup traps. First, if you write a JUnit test as fun test() = runBlocking { ... assertThat(x).isZero() }, the function’s return type becomes the assertion type instead of Unit, and JUnit silently skips it—3 of my 12 reproduction tests didn’t run until I added an explicit : Unit. Second, if a finally block needs to call a suspending cleanup function, wrap it in withContext(NonCancellable) so it still executes while the coroutine is cancelling.

Checklist

Cancellation is a control signal delivered as an exception. Swallowing it breaks the core contract of structured concurrency: when a parent finishes, all of its children stop with it.

  • Does every catch (e: Exception) or catch (e: Throwable) inside a coroutine rethrow CancellationException or call ensureActive()?
  • Have all runCatching calls wrapping suspending functions been replaced with a cancellation-safe helper?
  • Are all-or-nothing parallel calls using coroutineScope, and independent tasks using supervisorScope with explicit per-child error handling?
  • Are withTimeout exceptions converted so they don’t vanish in top-level launch, and are blocking I/O calls wrapped in runInterruptible?
  • Are background workers running on a bean-owned CoroutineScope cancelled in @PreDestroy instead of GlobalScope?
This post is licensed under CC BY 4.0 by the author.