-
Notifications
You must be signed in to change notification settings - Fork 24
What is Structured concurrency
Devrath edited this page Jan 12, 2024
·
12 revisions
Structured concurrency is a way of executing the concurrent code so that proper management of resources and the flow of control is done.
In co-routines, provides some rules for managing the concurrency and execution of concurrent tasks in a controlled and disciplined manner.
In traditional concurrency models such as threads
or callback-based
systems, It is challenging to manage the lifecycle of concurrent tasks -> Structured concurrency addresses this by a properly structured and hierarchical approach to manage it.
Create a scope and launch the co-routines within the scope so that when the scope is canceled, all the co-routines in it are canceled.
class SimpleStructuredConcurrencyDemoVm @Inject constructor( ) : ViewModel() {
// Create a root co-routine scope
private val rootScope = CoroutineScope(Dispatchers.Default)
fun start() {
// Launch a co-routine within the scope
rootScope.launch {
println("Start outer coroutine")
// Create a nested co-routine scope
val nestedScope = CoroutineScope(Dispatchers.Default)
// Launch a new co-routine within the nested scope
nestedScope.launch {
println("Start inner coroutine")
delay(1000) // Observe we keep delay longer here than the outer delay
println("End inner coroutine")
}
delay(500) // Observe we have kept outer delay lesser than inner delay
println("End outer coroutine")
}
}
}
Start outer coroutine
Start inner coroutine
End outer coroutine
End inner coroutine
- The two co-routines are started one after another, Starting with the outer co-routine followed by the nested inner co-routine
- But observe the outer co-routine is completed and only then the inner co-routine is complete because the inner coroutine has a delay greater than the outer coroutine.