Home > Software design >  Different behavior of awaitAll() in Kotlin Coroutines
Different behavior of awaitAll() in Kotlin Coroutines

Time:09-01

When we execute following functions after warmup, we get two different results.

  • good(): 7ms
  • bad(): 618ms

Why repeating outside the coroutineScope{...} get a result that looks like invoking in serial?

suspend fun good() =
    buildList {
        coroutineScope {
            // repeat inside the coroutineScope
            repeat(100) {
                add(async { delay(5) })
            }
        }
    }.awaitAll()

suspend fun bad() =
    buildList {
        // repeat out of the coroutineScope
        repeat(100) {
            coroutineScope {
                add(async { delay(5) })
            }
        }
    }.awaitAll()

suspend fun main() {
    // do some warm up
    measureTimeMillis { good() }
        .also { println("good: ${it}ms") }
    measureTimeMillis { bad() }
        .also { println("bad: ${it}ms") }
}

CodePudding user response:

As the documentation of the coroutineScope function states:

This function returns as soon as the given block and all its children coroutines are completed.

Calling coroutineScope suspends until all of its children coroutines are complete, so your bad() example is running the jobs serially by design.

  • Related