Job lifecycle and cancellation in Kotlin - Time & Space Complexity
When working with Kotlin coroutines, understanding how job lifecycle and cancellation affect performance is important.
We want to know how the time cost changes as more jobs are created and cancelled.
Analyze the time complexity of the following code snippet.
val jobs = mutableListOf()
repeat(n) { i ->
val job = GlobalScope.launch {
delay(1000L)
println("Job $i done")
}
jobs.add(job)
}
jobs.forEach { it.cancel() }
This code launches n coroutines (jobs) and then cancels all of them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Launching n jobs in a loop and then cancelling n jobs in another loop.
- How many times: Each loop runs n times, so launching and cancelling happen n times each.
As the number of jobs n increases, the total operations grow roughly in proportion to n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 launches + 10 cancels) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The total work grows linearly as n grows.
Time Complexity: O(n)
This means the time to launch and cancel jobs grows directly with the number of jobs.
[X] Wrong: "Cancelling all jobs happens instantly no matter how many jobs there are."
[OK] Correct: Each job must be individually cancelled, so cancelling takes time proportional to the number of jobs.
Understanding how job lifecycle operations scale helps you write efficient concurrent code and explain your reasoning clearly in interviews.
"What if we cancelled jobs one by one inside the launch block instead of after launching all? How would the time complexity change?"