A beginner question about how dispatchers work in Kotlin. I run this piece of code to test a theory and it printed out the thread names are “DefaultDispatcher-worker-xx” even though I specifically call launch(Dispatchers.IO). I never actually see the log showing as Dispatchers.IO anywhere in my code despite using withContext(Dispatchers.IO) in various places. How does it work?
import kotlinx.coroutines.*
fun main() = runBlocking {
println("${Thread.currentThread().name} - Start")
repeat(50) {
launch(Dispatchers.IO) { performIO(it) }
}
}
suspend fun performIO(number: Int) {
println("${Thread.currentThread().name} - Perform IO $number")
delay(2000L)
}
// even this doesn't show as expected
suspend fun performIO(number: Int) = withContext(Dispatchers.IO) {
println("${Thread.currentThread().name} - Perform IO $number")
delay(2000L)
}
The log looks like this
main - Start
DefaultDispatcher-worker-24 - Perform IO 18
DefaultDispatcher-worker-32 - Perform IO 30
.....
DefaultDispatcher-worker-12 - Perform IO 11
DefaultDispatcher-worker-17 - Perform IO 13
And second question, it says here in the document: By default, the maximum number of threads used by this dispatcher is equal to the number of CPU cores, but is at least two. My laptop has 10 CPU cores, but the log here shows the thread name ranging from 1 to 5x. It’s likely around 50 different threads? Why?
visiblesail is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.