Skip to content

What is Structured concurrency

Devrath edited this page Jan 12, 2024 · 12 revisions

Basic meaning of concurrency

Structured concurrency is a way of executing the concurrent code so that proper management of resources and the flow of control is done.

In the context of co-routines

In co-routines, provides some rules for managing the concurrency and execution of concurrent tasks in a controlled and disciplined manner.

Challenges faced by other approaches to concurrency

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.

Basic Idea

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.

Code

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")
        }
    }


}

Output

Start outer coroutine
Start inner coroutine
End outer coroutine
End inner coroutine

Observations

  • 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.
Clone this wiki locally