Hey everybody. I have a quick question. In this ex...
# coroutines
o
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.
Copy code
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.
Copy code
first started
joining
second started
first finished
second finished
complete
z
add the current Thread ID to your log messages, might give a hint
c
👆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
Thank you!