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:
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.
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 delay
s 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}")
}