0
0
Kotlinprogramming~5 mins

Job lifecycle and cancellation in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Job lifecycle and cancellation
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of jobs n increases, the total operations grow roughly in proportion to n.

Input Size (n)Approx. Operations
10About 20 operations (10 launches + 10 cancels)
100About 200 operations
1000About 2000 operations

Pattern observation: The total work grows linearly as n grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to launch and cancel jobs grows directly with the number of jobs.

Common Mistake

[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.

Interview Connect

Understanding how job lifecycle operations scale helps you write efficient concurrent code and explain your reasoning clearly in interviews.

Self-Check

"What if we cancelled jobs one by one inside the launch block instead of after launching all? How would the time complexity change?"