SupervisorJob vs Job: Failure Isolation
Use SupervisorJob to prevent one child's failure from cancelling siblings.
SupervisorJob vs Job: Failure Isolation is a free Kotlin Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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()
}supervisorScope Builder
supervisorScope { } creates a scope with a SupervisorJob as parent. It is the idiomatic way to run independent children.
import kotlinx.coroutines.*
fun main() = runBlocking {
supervisorScope {
val job1 = launch {
throw RuntimeException("job1 failed")
}
val job2 = launch {
delay(100)
println("job2 succeeded")
}
job1.join() // wait for job1 (it failed)
job2.join() // job2 is unaffected
}
}Catching Child Failures
With supervisorScope, each child handles its own exception. Unhandled exceptions in children must be caught per-child.
import kotlinx.coroutines.*
fun main() = runBlocking {
supervisorScope {
val result = async {
delay(50)
throw RuntimeException("async failed")
}
try {
result.await()
} catch (e: RuntimeException) {
println("Caught from async: ${e.message}")
}
println("Scope continues")
}
}Job vs SupervisorJob at Scope Creation
Pass SupervisorJob() when creating a CoroutineScope for a service or ViewModel that should survive individual child failures.
import kotlinx.coroutines.*
class MyService {
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
fun startTask(name: String) {
scope.launch {
if (name == "fail") throw RuntimeException("$name failed")
println("$name done")
}
}
fun stop() = scope.cancel()
}
fun main() = runBlocking {
val svc = MyService()
svc.startTask("fail")
svc.startTask("ok")
delay(100)
svc.stop()
}viewModelScope Uses SupervisorJob
Android's viewModelScope is backed by a SupervisorJob. One failed launch does not cancel the ViewModel's other coroutines.
import kotlinx.coroutines.*
// Android ViewModel internals:
// val viewModelScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
// Each launch is independent — one failure doesn't crash the ViewModel
fun main() = runBlocking {
println("viewModelScope = SupervisorJob + Main")
}Parallel Decomposition with supervisorScope
Use supervisorScope + async for parallel tasks where some may fail without affecting others.
import kotlinx.coroutines.*
fun main() = runBlocking {
val results = supervisorScope {
val a = async { delay(50); "result-A" }
val b = async { throw RuntimeException("B failed") }
val c = async { delay(30); "result-C" }
listOf(
runCatching { a.await() },
runCatching { b.await() },
runCatching { c.await() }
)
}
results.forEach { println(it) }
}When to Use Regular Job
Use regular Job (coroutineScope) when all children must succeed together — one failure should abort the group. Like a transaction: all or nothing.
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
coroutineScope { // regular Job
val a = async { delay(50); "A" }
val b = async { throw RuntimeException("B failed") }
println(a.await())
println(b.await()) // throws — cancels a too
}
} catch (e: RuntimeException) {
println("Transaction failed: ${e.message}")
}
}Exception Propagation in supervisorScope
In supervisorScope, an exception propagates to the scope only if it escapes the child's top-level — i.e., no try-catch in the child. The parent does not see it.
import kotlinx.coroutines.*
fun main() = runBlocking {
supervisorScope {
// Exception caught inside child — scope unaffected
launch {
try { throw RuntimeException("handled") }
catch (e: Exception) { println("Child caught: ${e.message}") }
}
delay(100)
println("Scope survived")
}
}CoroutineExceptionHandler with SupervisorJob
Install a CoroutineExceptionHandler in a supervisor scope to log or react to uncaught child failures without crashing the scope.
import kotlinx.coroutines.*
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, e ->
println("Uncaught: ${e.message}")
}
val scope = CoroutineScope(SupervisorJob() + handler)
scope.launch { throw RuntimeException("unhandled failure") }
scope.launch { delay(100); println("still running") }
delay(200)
scope.cancel()
}Failure Isolation Summary
Job: one child fails → all fail. SupervisorJob: children fail independently. Use supervisor for services and ViewModels; regular Job for transactional groups.
import kotlinx.coroutines.*
// Decision table:
// coroutineScope { } -> Job: all-or-nothing
// supervisorScope { } -> SupervisorJob: independent failures
// CoroutineScope(SupervisorJob()) -> long-lived service
fun main() = runBlocking { println("Pick the right job for the right scope") }Quick Check
Which scope prevents a child failure from cancelling its siblings?
Recap
Job: failure cascades to siblings. SupervisorJob/supervisorScope: failures are isolated per child. Use supervisorScope for parallel independent tasks; regular coroutineScope for transactional groups.
Frequently asked questions
Is the “SupervisorJob vs Job: Failure Isolation” lesson free?
Yes — the full text of “SupervisorJob vs Job: Failure Isolation” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “SupervisorJob vs Job: Failure Isolation”?
Use SupervisorJob to prevent one child's failure from cancelling siblings. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “SupervisorJob vs Job: Failure Isolation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- SupervisorJob vs Job: Failure Isolation
- CoroutineExceptionHandler: Global Uncaught Handler
- async/await Exception Propagation
- Designing Resilient Coroutine Architectures