Predict the output
Roughly how long does this take on a normal laptop?
fun main() = runBlocking {
val start = System.currentTimeMillis()
val jobs = List(10_000) {
launch { delay(1_000) }
}
jobs.joinAll()
println(if (System.currentTimeMillis() - start < 3_000) "about 1 s" else "much longer")
}Hint 1 of 2
Does delay block the thread?
Hint 2 of 2
How many threads does runBlocking use here?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A About 1 second
Correct. All 10,000 coroutines suspend at the same time on one thread, so they finish together.
Why not the others?
- B About 10,000 seconds. That would be true if each delay blocked the only thread in turn. delay suspends instead.
- C It runs out of memory. Suspended coroutines are small heap objects; 10,000 is nothing.
- D It never finishes because runBlocking has one thread. One thread is enough because nobody blocks it.