Structured concurrency helps keep your program clean by making sure all tasks finish or stop together. This stops tasks from running forever and using up memory or resources.
Why structured concurrency prevents leaks in Kotlin
coroutineScope {
launch {
// child coroutine work
}
// other work
}coroutineScope creates a block where all launched tasks must complete before moving on.
If any child task fails, the whole scope cancels all tasks to avoid leaks.
suspend fun example() = coroutineScope { launch { println("Task 1 started") delay(1000) println("Task 1 finished") } launch { println("Task 2 started") delay(500) println("Task 2 finished") } }
suspend fun example() = coroutineScope { val job = launch { while(true) { delay(100) println("Running") } } delay(500) job.cancel() // stops the infinite task }
This program starts a task inside a structured concurrency block. It waits for the task to finish before printing the final message. This shows how structured concurrency keeps tasks from leaking.
import kotlinx.coroutines.* suspend fun mainTask() = coroutineScope { launch { println("Starting task") delay(300) println("Task done") } println("Waiting for tasks to finish") } fun main() = runBlocking { mainTask() println("All tasks completed") }
Structured concurrency makes sure no task is left running in the background.
If a child task fails, all sibling tasks are cancelled to keep the program clean.
Using coroutineScope or supervisorScope helps manage task lifetimes clearly.
Structured concurrency groups tasks so they start and finish together.
This grouping prevents tasks from running forever and leaking resources.
It makes your program safer and easier to understand.