SupervisorJob vs Job: Failure Isolation
Use SupervisorJob to prevent one child's failure from cancelling siblings.
Default Job Failure Propagation
With a regular Job, a child failure cancels the parent, which cancels all siblings. One failure brings down the whole hierarchy.
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope {
launch { delay(50); throw RuntimeException("child 1 failed") }
launch { delay(1000); println("child 2 — never prints") }
}
} catch (e: RuntimeException) {
println("Caught: ${e.message}")
}
}SupervisorJob Overview
SupervisorJob changes the rule: a child failure does NOT cancel siblings or the parent. Each child fails independently.
import kotlinx.coroutines.*
fun main() = runBlocking {
val supervisor = SupervisorJob()
val scope = CoroutineScope(coroutineContext + supervisor)
scope.launch { throw RuntimeException("child 1 failed") }
scope.launch { delay(100); println("child 2 still runs") }
delay(200)
supervisor.cancel()
}All lessons in this course
- SupervisorJob vs Job: Failure Isolation
- CoroutineExceptionHandler: Global Uncaught Handler
- async/await Exception Propagation
- Designing Resilient Coroutine Architectures