In the official guide “Cancellation and timeouts” section “Asynchronous timeout and resources” there is an example that is supposed to… “If you run the above code you’ll see that it does not always print zero, though it may depend on the timings of your machine you may need to tweak timeouts in this example to actually see non-zero values.”
var acquired = 0
class Resource {
init { acquired++ } // Acquire the resource
fun close() { acquired-- } // Release the resource
}
fun main() {
runBlocking {
repeat(100_000) { // Launch 100K coroutines
launch {
val resource = withTimeout(60) { // Timeout of 60 ms
delay(50) // Delay for 50 ms
Resource() // Acquire a resource and return it from withTimeout block
}
resource.close() // Release the resource
}
}
}
// Outside of runBlocking all coroutines have completed
println(acquired) // Print the number of resources still acquired
}
I do not understand how that work. If we let the timeout to 60, instances of Resource are never created. We had to go up to 120 to see instances been created. However 60ms looks enough to let include a delay(50) + an instance creation. No?
Does someone could explain that? Thanks in advance.