Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does Kotlin coroutines documentation mean when they say joinAll() is semantically equivalent to calling join() in sequence?

In https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/join-all.html it’s stated that "This method is semantically equivalent to joining all given jobs one by one with forEach { it.join() }."

I have this code

import kotlinx.coroutines.*

fun main() {
  joinTest()
  joinAllTest()
}

fun joinAllTest() {
  val begin = System.currentTimeMillis()
  runBlocking { (0..2).map { launch { delay1s(it) } }.joinAll() }
  val end = System.currentTimeMillis()

  println("joinAllTest took: ${end-begin}")
}

fun joinTest() {
  val begin = System.currentTimeMillis()
  runBlocking {
    for (i in 0..2) {
      val job2 = launch { delay1s(i) }
      job2.join()
    }
  }
  val end = System.currentTimeMillis()

  println("joinTest took: ${end-begin}")
}


suspend fun delay1s(i: Int) {
  delay(1000)
}

This produces:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

joinTest took: 3101
joinAllTest took: 1011

How can join() be semantically equivalent to joinAll() with the following behavior? Calling join sequentially suspends on each join while joinAll() runs them in parallel.

>Solution :

Relevant source code in kotlinx.coroutines

public suspend fun Collection<Job>.joinAll(): Unit = forEach { it.join() }

The implementation tells us that the joinAll function is literally equal to forEach { it.join() }

The reason for the different timings of your functions is that in the first case, the delays are performed in parallel, and in the second, each subsequent one waits for the previous one to complete.

So in your case joinTest should be:

fun joinTest() {
  val begin = System.currentTimeMillis()
  runBlocking { (0..2).map { launch { delay1s(it) } }.forEach{it.join()} }
  val end = System.currentTimeMillis()

  println("joinTest took: ${end-begin}")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading