0
0
Kotlinprogramming~5 mins

SupervisorJob for independent failure in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: SupervisorJob for independent failure
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a coroutine with a SupervisorJob changes as we add more child coroutines.

Specifically, we ask: how does failure in one child affect the overall execution time?

Scenario Under Consideration

Analyze the time complexity of the following Kotlin coroutine code using SupervisorJob.


val supervisor = SupervisorJob()
val scope = CoroutineScope(Dispatchers.Default + supervisor)

repeat(n) { i ->
    scope.launch {
        delay(100L)
        if (i == 0) throw Exception("Fail")
    }
}

scope.coroutineContext[Job]?.join()
    

This code launches n child coroutines under a SupervisorJob, where one child fails independently.

Identify Repeating Operations

Look for loops or repeated tasks that affect time.

  • Primary operation: Launching and running n child coroutines.
  • How many times: The repeat loop runs n times, creating n coroutines.
How Execution Grows With Input

Each coroutine runs independently and takes about the same time, even if one fails.

Input Size (n)Approx. Operations
1010 coroutines run, one fails, others continue
100100 coroutines run, failure in one does not stop others
10001000 coroutines run independently, failure isolated

Pattern observation: The total work grows linearly with n, and failure in one coroutine does not slow down others.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows roughly in direct proportion to the number of coroutines launched.

Common Mistake

[X] Wrong: "If one coroutine fails, all others stop immediately, so total time is constant."

[OK] Correct: With SupervisorJob, failure in one child does not cancel siblings, so all coroutines still run independently.

Interview Connect

Understanding how SupervisorJob isolates failures helps you explain concurrency control and error handling clearly in interviews.

Self-Check

"What if we replaced SupervisorJob with a regular Job? How would the time complexity change when one coroutine fails?"