Structured concurrency and CancellationException in Kotlin
Why catch(Exception) and runCatching break coroutine cancellation, plus benchmarks for coroutineScope, supervisorScope, withTimeout, and GlobalScope.
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
CancellationExceptionlike a normal runtime error. Here are five cancellation traps reproduced in tests, measured locally, and fixed cleanly.
Tested with Kotlin 2.1.0,
kotlinx.coroutines1.10.1, Spring Boot 3.4.2, Java 21, and Gradle 8.12.1. Because Spring Boot 3.4.2’s BOM pinskotlinx.coroutinesto 1.8.1, I overrode it withextra["kotlin-coroutines.version"] = "1.10.1". All numbers come from running./gradlew testthree 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:
| Scenario | Measured result (3 runs) |
|---|---|
catch (e: Exception) then cancel | join() timed out after 1s; catch ran 450k–570k times |
ensureActive() inside catch | cancelAndJoin() finished in 0.76–0.84ms, 0 swallowed |
runCatching + getOrElse | Caught JobCancellationException and saved the fallback value |
GlobalScope.launch worker | Kept firing 16 more ticks in the 1s after context shutdown |
Bean-owned scope + @PreDestroy cancel | 0 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.
| Construct | Duration (3 runs) | Behavior |
|---|---|---|
coroutineScope + launch | 105–118ms | Both siblings cancelled at 104–117ms; exception propagated to caller |
supervisorScope + launch | 303–305ms | Both siblings completed; failure went to CoroutineExceptionHandler |
supervisorScope + async | 303–318ms | Returned [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
| Requirement | Choice | Reason |
|---|---|---|
| Parallel calls where one failure invalidates the whole response | coroutineScope + async | Cancels siblings immediately and propagates the error |
| Independent tasks where partial failure is acceptable | supervisorScope + per-child error handling | Isolates failure from sibling coroutines |
| Treat a timeout as a missing value | withTimeoutOrNull | Branches on null without exception flow |
| Surface a timeout to callers as an error | withTimeout mapped to a domain exception | Prevents silent drops in top-level launch |
| Apply a timeout to blocking I/O | runInterruptible | Interrupts 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 ofUnit, and JUnit silently skips it—3 of my 12 reproduction tests didn’t run until I added an explicit: Unit. Second, if afinallyblock needs to call a suspending cleanup function, wrap it inwithContext(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)orcatch (e: Throwable)inside a coroutine rethrowCancellationExceptionor callensureActive()? - Have all
runCatchingcalls wrapping suspending functions been replaced with a cancellation-safe helper? - Are all-or-nothing parallel calls using
coroutineScope, and independent tasks usingsupervisorScopewith explicit per-child error handling? - Are
withTimeoutexceptions converted so they don’t vanish in top-levellaunch, and are blocking I/O calls wrapped inrunInterruptible? - Are background workers running on a bean-owned
CoroutineScopecancelled in@PreDestroyinstead ofGlobalScope?