CancellationException behavior in Kotlin - Time & Space Complexity
When working with Kotlin coroutines, it's important to understand how cancellation affects program flow.
We want to see how the CancellationException influences the running time of coroutine code.
Analyze the time complexity of the following coroutine code snippet.
suspend fun processItems(items: List<Int>) {
for (item in items) {
if (!kotlin.coroutines.coroutineContext.isActive) throw CancellationException()
delay(10) // simulate work
println(item)
}
}
This code processes a list of items, checking for cancellation before each step.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for each item in the input list.
Each item causes a check for cancellation and a small delay, so work grows with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 cancellation checks + 10 delays |
| 100 | 100 cancellation checks + 100 delays |
| 1000 | 1000 cancellation checks + 1000 delays |
Pattern observation: The total work increases directly with the number of items.
Time Complexity: O(n)
This means the time grows linearly with the number of items processed.
[X] Wrong: "CancellationException makes the loop stop immediately, so time is constant."
[OK] Correct: Cancellation only stops the loop when detected; until then, all items are processed, so time depends on input size.
Understanding how cancellation affects coroutine loops helps you reason about program responsiveness and efficiency in real apps.
"What if the cancellation check was removed? How would the time complexity change?"