Trying to better understand when coroutines switch...
# coroutines
Trying to better understand when coroutines switch threads when moving from Default to IO and back. And when the thread should be reused, to try to better optimize what can be. I'm building some POC so some things should be implemented differently probably and that will explain the switches, but understanding what will help building the migration path. So I have a coroutineContext on Dispatchers.Default that call a
Copy code
launch {
	val result = function()
function is a suspend function that enqueue commands in a worker pool that works on Dispatchers.IO
Copy code
supend function () : Result {
	val result = workerpool.execute()
	return result
The actual coroutine that run in the worker pool is just
Copy code
doWork () : Result {
        try {
        } catch (e: Throwable) {
And here's the threads the different parts run in on different runs.
Copy code
T1: Pre queue 81396 DefaultDispatcher-worker-5
T3: Pre task 81396  DefaultDispatcher-worker-5
T4: Post task 81396 DefaultDispatcher-worker-5
T2: Post queue 81366 DefaultDispatcher-worker-1
Why is T2 switched to another thread? I suppose the IO thread is asked for removal before the end of the coroutine to keep the number of default thread constants? Is this normal and efficient?
Copy code
T1: Pre queue 81375 DefaultDispatcher-worker-2
T3: Pre task 81417  DefaultDispatcher-worker-7
T4: Post task 81417 DefaultDispatcher-worker-7
T2: Post queue 81423 DefaultDispatcher-worker-12
Here the switch to IO really switched to another thread. Should not the thread be converted to IO as per the doc? And same answer at the end why is there's another switch Without looking at the thread switching all works and fast, just wondering if there's something I miss as I suppose on larger scale the switch can have impact and from the docs it seemed some should not happens.
Trying to better understand when coroutines switch threads when moving from Default to IO and back.
It is an implementation detail which is not exposed to users. Default dispatcher may or may not switch threads depending on timing, system load and other factors which are not exposed to end users. The only guarantee dispatcher gives you is that there could be maximum 64 (by default, configurable) occupied threads in
threads in
. The rest is an implementation detail
The short answer is “there is some complicated heuristic which depends on work-stealing timing”
Ok so there's nothing I should try to optimize, just use default for computation and IO for blocking or low CPU long running things. And just a confirmation, default is now min 2 since 1.0 final right?
Yes, minimum is two
👍 1