I was just checking the behaviour of the Coroutine Dispatchers. So I was trying to understand how many threads each of these Dispatchers can create. To check this, I created a loop statement counting from 1 to 1_000_000.
In each loop iteration, I'm creating a coroutine with Dispatchers.IO, But when I see the output, it is not created 1_000_000 coroutines, and all these are DefaultDispatcher-worker threads, and it always stops execution in the range 40000-50000 randomly.
But when I replaced Dispatchers.IO with Dispatchers.Unconfined, it actually created all the 1_000_000 coroutines without fail and all these are created on Main thread.
So I need some help here to understand why Dispatchers.IO is failed in this case.
Dispatchers.IO:
fun main() {
println("Start of main")
val handler = CoroutineExceptionHandler { _, e -> e.printStackTrace() }
runBlocking {
for (i in 1..1000000) {
CoroutineScope(Dispatchers.IO + CoroutineName("Dispatchers.IO")).launch(handler) {
println("${Thread.currentThread().name} task number is :$i")
}
}
}
println("End of main")
}
Dispatchers.Unconfined
fun main() {
println("Start of main")
val handler = CoroutineExceptionHandler { _, e ->
e.printStackTrace()
}
runBlocking {
for (i in 1..1000000) {
CoroutineScope(Dispatchers.Unconfined + CoroutineName("Dispatchers.Unconfined")).launch(handler) {
println("${Thread.currentThread().name} task number is :$i")
}
}
}
println("End of main")
}
Thanks in advance