https://kotlinlang.org logo
Title
o

Oleg Siboglov

10/14/2020, 7:09 PM
Hey everybody. I have a quick question. In this example, why does
joining
occur before
second started
? I’m running this in IntelliJ if that makes any difference.
fun main() = runBlocking {
    val job = GlobalScope.launch {
        val deferredOne = async(<http://Dispatchers.IO|Dispatchers.IO>) {
            println("first started")
            delay(1_000)
            println("first finished")
        }
        val deferredTwo = async(<http://Dispatchers.IO|Dispatchers.IO>) {
            println("second started")
            delay(2_500)
            println("second finished")
        }
        println("joining")
        deferredOne.join()
        deferredTwo.join()
        println("complete")
    }
    job.join()
}
This is the output.
first started
joining
second started
first finished
second finished
complete
z

Zach Klippenstein (he/him) [MOD]

10/14/2020, 7:12 PM
add the current Thread ID to your log messages, might give a hint
c

Casey Brooks

10/14/2020, 7:24 PM
👆Yes, it’s because the block inside
async
is being run…well…async. The calling thread/coroutine is not going to wait for it to be started or run before continuing itself. Calling
async
is basically sending a request into a queue, and the Schedulers.IO thread poll will pull tasks out of that queue as threads become available.
o

Oleg Siboglov

10/14/2020, 8:55 PM
Thank you!