📖 Scenario: Imagine you are building a simple Kotlin program that launches multiple tasks to fetch data. You want to make sure that when the main task finishes, all child tasks are properly cleaned up and no background work keeps running forever, which can cause memory leaks.
🎯 Goal: You will create a Kotlin program that uses structured concurrency to launch child coroutines inside a scope. You will see how structured concurrency helps prevent leaks by automatically cancelling child tasks when the parent finishes.
📋 What You'll Learn
Create a CoroutineScope with runBlocking
Launch two child coroutines inside the scope
Use delay to simulate work in child coroutines
Cancel the parent scope to stop all child coroutines
Print messages to show when coroutines start and finish
💡 Why This Matters
🌍 Real World
Structured concurrency is used in Kotlin apps to manage background tasks safely, avoiding memory leaks and unexpected behavior.
💼 Career
Understanding structured concurrency is important for Kotlin developers working on Android apps or backend services to write reliable and maintainable asynchronous code.
Progress0 / 4 steps
1
Create a runBlocking scope
Write a Kotlin program that starts with fun main() and inside it, create a runBlocking block assigned to scope.
Kotlin
Hint
Use val scope = runBlocking { } inside main to create a coroutine scope.
2
Launch two child coroutines inside scope
Inside the runBlocking block assigned to scope, launch two child coroutines named job1 and job2 using launch. Each coroutine should print a start message, delay for 1000 milliseconds, then print a finish message.
Kotlin
Hint
Use val job1 = launch { ... } and val job2 = launch { ... } inside runBlocking.
3
Cancel the scope to stop all child coroutines
After launching job1 and job2, add a line to cancel the scope using scope.cancel(). This will stop all running child coroutines.
Kotlin
Hint
Call cancel() inside runBlocking to stop all child coroutines.
4
Print a message after cancelling to show completion
After the runBlocking block, add a println statement that prints "Scope cancelled, all child coroutines stopped".
Kotlin
Hint
Use println("Scope cancelled, all child coroutines stopped") after the runBlocking block.
Practice
(1/5)
1. What is the main reason structured concurrency helps prevent resource leaks in Kotlin?
easy
A. It requires manual task cancellation by the programmer.
B. It automatically frees memory after each line of code.
C. It disables background tasks after 5 seconds.
D. It ensures all tasks start and finish together, avoiding orphaned tasks.
Solution
Step 1: Understand structured concurrency concept
Structured concurrency groups related tasks so they start and finish as a unit.
Step 2: Link grouping to resource management
This grouping prevents tasks from running forever and leaking resources by ensuring no orphaned tasks remain.
Final Answer:
It ensures all tasks start and finish together, avoiding orphaned tasks. -> Option D
Quick Check:
Grouping tasks = prevents leaks [OK]
Hint: Think: tasks grouped start and end together [OK]
Common Mistakes:
Confusing automatic memory freeing with concurrency
Believing tasks stop after fixed time automatically
Assuming manual cancellation is always required
2. Which Kotlin syntax correctly starts a structured concurrency block using coroutineScope?
easy
A. launch { coroutineScope { /* task */ } }
B. coroutineScope() -> launch { /* task */ }
C. coroutineScope { launch { /* task */ } }
D. launch coroutineScope { /* task */ }
Solution
Step 1: Recall coroutineScope usage
In Kotlin, coroutineScope is a suspending function that takes a lambda block where child coroutines run.
Step 2: Identify correct syntax
The correct syntax is coroutineScope { launch { /* task */ } } which starts a structured block with a child coroutine.
Thinking delay is required before printing main done
Believing runBlocking disallows launch
Misunderstanding println placement
5. You want to run multiple tasks concurrently but ensure none leak after completion. Which Kotlin approach best applies structured concurrency to prevent leaks?
hard
A. Use coroutineScope or supervisorScope to launch child coroutines inside a suspending block.
B. Launch all tasks with GlobalScope.launch and manually cancel them later.
C. Run tasks sequentially without coroutines to avoid leaks.
D. Use runBlocking only for all tasks without launching coroutines.
Solution
Step 1: Identify structured concurrency tools
coroutineScope and supervisorScope provide structured concurrency by grouping child coroutines and waiting for their completion.