Bird
Raised Fist0
Kotlinprogramming~20 mins

SupervisorJob for independent failure in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
SupervisorJob Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Kotlin coroutine code using SupervisorJob?
Consider the following Kotlin code snippet using SupervisorJob. What will be printed when it runs?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val supervisor = SupervisorJob()
    val scope = CoroutineScope(coroutineContext + supervisor)

    val child1 = scope.launch {
        delay(100)
        println("Child 1 completed")
    }

    val child2 = scope.launch {
        delay(50)
        throw RuntimeException("Child 2 failed")
    }

    child1.join()
    try {
        child2.join()
    } catch (e: Exception) {
        // Child 2 failure ignored
    }
    println("Scope is active: ${scope.isActive}")
}
AChild 2 failed exception is ignored, Child 1 is cancelled, then prints: Scope is active: false
BChild 2 failed exception is thrown and Child 1 is cancelled, no further output.
CChild 2 failed exception is thrown, Child 1 completes, then prints: Scope is active: false
DChild 2 failed exception is ignored, Child 1 completes, then prints: Scope is active: true
Attempts:
2 left
๐Ÿ’ก Hint
SupervisorJob allows child coroutines to fail independently without cancelling siblings.
๐Ÿง  Conceptual
intermediate
1:30remaining
Why use SupervisorJob in Kotlin coroutines?
Which of the following best explains the main purpose of using SupervisorJob in Kotlin coroutines?
ATo ensure that if one child coroutine fails, all sibling coroutines are cancelled immediately.
BTo allow child coroutines to fail independently without cancelling their siblings or the parent scope.
CTo automatically restart failed child coroutines without manual intervention.
DTo run all child coroutines sequentially instead of concurrently.
Attempts:
2 left
๐Ÿ’ก Hint
Think about failure isolation between child coroutines.
๐Ÿ”ง Debug
advanced
2:30remaining
Identify the error in this coroutine code using SupervisorJob
This Kotlin code intends to use SupervisorJob to isolate child coroutine failures. What is the error causing the program to not behave as expected?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val supervisor = SupervisorJob()
    val scope = CoroutineScope(coroutineContext + supervisor)

    val child1 = scope.launch {
        delay(100)
        println("Child 1 done")
    }

    val child2 = scope.launch {
        delay(50)
        throw Exception("Child 2 error")
    }

    child1.join()
    child2.join()
    println("Done")
}
AThe CoroutineScope is missing the coroutineContext, so SupervisorJob is not combined with Dispatchers, causing unexpected behavior.
BSupervisorJob should be replaced with Job to isolate failures properly.
CThe child coroutines are not launched with async, so exceptions are not caught.
DThe delay times cause child1 to finish before child2 throws an exception, so no error is observed.
Attempts:
2 left
๐Ÿ’ก Hint
Check how CoroutineScope is created with context elements.
โ“ Predict Output
advanced
2:30remaining
What happens to the parent scope when a child coroutine fails with SupervisorJob?
Given this Kotlin code, what will be the output and state of the parent scope after child2 fails?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val supervisor = SupervisorJob()
    val scope = CoroutineScope(coroutineContext + supervisor)

    val child1 = scope.launch {
        delay(100)
        println("Child 1 finished")
    }

    val child2 = scope.launch {
        delay(50)
        throw IllegalStateException("Child 2 failed")
    }

    try {
        child2.join()
    } catch (e: Exception) {
        println("Caught exception: ${e.message}")
    }

    println("Parent scope active: ${scope.isActive}")
    child1.join()
}
A
Caught exception: Child 2 failed
Parent scope active: true
Child 1 finished
B
Caught exception: Child 2 failed
Parent scope active: false
Child 1 finished
C
No exception caught
Parent scope active: false
Child 1 finished
D
No exception caught
Parent scope active: true
Child 1 finished
Attempts:
2 left
๐Ÿ’ก Hint
SupervisorJob prevents parent cancellation on child failure.
๐Ÿง  Conceptual
expert
3:00remaining
How does SupervisorJob affect exception propagation in Kotlin coroutines?
Which statement best describes how SupervisorJob changes exception propagation compared to a regular Job in Kotlin coroutines?
ASupervisorJob propagates exceptions from any child coroutine to the parent immediately, cancelling all siblings.
BSupervisorJob suppresses all exceptions from child coroutines, so the parent never sees any failures.
CSupervisorJob allows child coroutines to fail independently; exceptions do not cancel siblings or the parent, but are still propagated to the parentโ€™s handler if unhandled.
DSupervisorJob queues exceptions from child coroutines and throws them only after all children complete.
Attempts:
2 left
๐Ÿ’ก Hint
Think about failure isolation and exception visibility.

Practice

(1/5)
1. What is the main purpose of SupervisorJob in Kotlin coroutines?
easy
A. To cancel all child coroutines when one fails
B. To allow child coroutines to fail independently without cancelling siblings
C. To delay coroutine execution until all children complete
D. To automatically restart failed coroutines

Solution

  1. Step 1: Understand SupervisorJob behavior

    SupervisorJob lets child coroutines run independently so one failure doesn't affect others.
  2. Step 2: Compare with regular Job

    Regular Job cancels all children if one fails, but SupervisorJob prevents this.
  3. Final Answer:

    To allow child coroutines to fail independently without cancelling siblings -> Option B
  4. Quick Check:

    SupervisorJob = independent failure [OK]
Hint: Remember: SupervisorJob isolates failures among children [OK]
Common Mistakes:
  • Thinking SupervisorJob cancels all children on failure
  • Confusing SupervisorJob with CoroutineScope
  • Assuming SupervisorJob restarts failed coroutines
2. Which of the following is the correct way to create a CoroutineScope with a SupervisorJob?
easy
A. val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
B. val scope = CoroutineScope(SupervisorJob)
C. val scope = CoroutineScope(Job() + Dispatchers.Default)
D. val scope = CoroutineScope(Dispatchers.Default)

Solution

  1. Step 1: Identify correct SupervisorJob usage

    Creating a scope with SupervisorJob() instance plus a dispatcher is correct syntax.
  2. Step 2: Check options for syntax correctness

    val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) uses SupervisorJob() constructor and adds dispatcher, which is valid.
  3. Final Answer:

    val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) -> Option A
  4. Quick Check:

    SupervisorJob() + Dispatcher = correct scope [OK]
Hint: Use SupervisorJob() with + operator to add dispatcher [OK]
Common Mistakes:
  • Using SupervisorJob without parentheses
  • Not adding a dispatcher to CoroutineScope
  • Using Job() instead of SupervisorJob()
3. Consider this Kotlin code snippet using SupervisorJob:
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
scope.launch {
  launch { throw Exception("Child 1 failed") }
  launch { delay(100); println("Child 2 completed") }
}
What will be printed when this code runs?
medium
A. Child 2 completed
B. Child 1 failed
C. Exception thrown and program crashes
D. No output, both coroutines are cancelled

Solution

  1. Step 1: Analyze SupervisorJob effect on children

    With SupervisorJob, failure in one child does not cancel siblings.
  2. Step 2: Trace coroutine execution

    Child 1 throws exception immediately, but Child 2 delays and then prints "Child 2 completed".
  3. Final Answer:

    Child 2 completed -> Option A
  4. Quick Check:

    SupervisorJob allows sibling to finish [OK]
Hint: Child failure won't cancel siblings with SupervisorJob [OK]
Common Mistakes:
  • Assuming all children cancel on one failure
  • Expecting no output due to exception
  • Confusing exception print with println output
4. Identify the error in this Kotlin coroutine code using SupervisorJob:
val scope = CoroutineScope(SupervisorJob)
scope.launch {
  launch { throw Exception("Error") }
  launch { println("Running") }
}
medium
A. launch cannot be called inside another launch
B. Child coroutines cannot throw exceptions
C. CoroutineScope cannot be created without a dispatcher
D. SupervisorJob is used without parentheses, causing a syntax error

Solution

  1. Step 1: Check SupervisorJob usage

    SupervisorJob is a function and must be called with parentheses SupervisorJob().
  2. Step 2: Validate CoroutineScope creation

    Using SupervisorJob without parentheses is a syntax error; it must be an instance.
  3. Final Answer:

    SupervisorJob is used without parentheses, causing a syntax error -> Option D
  4. Quick Check:

    SupervisorJob() requires parentheses [OK]
Hint: Always call SupervisorJob() with parentheses [OK]
Common Mistakes:
  • Omitting parentheses on SupervisorJob
  • Thinking nested launch is invalid
  • Assuming dispatcher is mandatory (optional)
5. You want to launch three child coroutines where failure of one should NOT cancel the others. Which setup correctly achieves this using SupervisorJob and handles exceptions independently?
hard
A. Use CoroutineScope(SupervisorJob()) but do not handle exceptions in children
B. Use CoroutineScope(Job()) and rely on default cancellation
C. Use CoroutineScope(SupervisorJob()) and wrap each child launch in try-catch blocks
D. Use GlobalScope without SupervisorJob

Solution

  1. Step 1: Choose SupervisorJob for independent failure

    Using SupervisorJob() allows children to fail independently without cancelling siblings.
  2. Step 2: Handle exceptions in each child

    Wrapping each child launch in try-catch blocks ensures exceptions are caught and handled independently within each coroutine.
  3. Final Answer:

    Use CoroutineScope(SupervisorJob()) and wrap each child launch in try-catch blocks -> Option C
  4. Quick Check:

    SupervisorJob + try-catch = safe independent children [OK]
Hint: Combine SupervisorJob with try-catch in children [OK]
Common Mistakes:
  • Ignoring exception handling in children
  • Using Job() which cancels siblings on failure
  • Using GlobalScope without SupervisorJob
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard