According to the document of Dispatchers.IO
This dispatcher shares threads with the [Default][Dispatchers.Default] dispatcher,
so using `withContext(Dispatchers.IO) { ... }` when already running on the [Default][Dispatchers.Default] dispatcher
does not lead to an actual switching to another thread - typically execution continues in the same thread.
As a result of thread sharing, more than 64 (default parallelism) threads can be created (but not used) during operations over IO dispatcher.
My test code is:
fun main(args: Array<String>) = runBlocking {
repeat(4) {
launch(Dispatchers.Default) {
println("Start $it in ${Thread.currentThread().name}")
withContext(Dispatchers.IO) {
println("Continue $it in ${Thread.currentThread().name}")
delay(10)
println("Resume $it in ${Thread.currentThread().name}")
}
}
}
}
Code explain: Creating 4 coroutine running with Default
dispatcher, switching to IO
dispatcher, then delay the coroutine for 10ms and resume.
I would expect that every coroutine will start
and continue
in the same thread as mentioned in the above doc, then might resume in another thread. But when I run the code, the output shows me a different result.
Start 0 in DefaultDispatcher-worker-1
Start 1 in DefaultDispatcher-worker-2
Start 2 in DefaultDispatcher-worker-3
Start 3 in DefaultDispatcher-worker-4
Continue 0 in DefaultDispatcher-worker-6
Continue 1 in DefaultDispatcher-worker-5
Continue 2 in DefaultDispatcher-worker-2
Continue 3 in DefaultDispatcher-worker-1
Resume 0 in DefaultDispatcher-worker-5
Resume 1 in DefaultDispatcher-worker-2
Resume 2 in DefaultDispatcher-worker-11
Resume 3 in DefaultDispatcher-worker-6
As you can see, coroutine 0 starts in thread 1 and continue in thread 6 after withContext
. The same for other coroutines.
Could anybody explain why?