Hello, let's say I have a blocking call to make (l...
# coroutines
a
Hello, let's say I have a blocking call to make (like a process builder call or ImageIO.createImageReader()), I currently use
runBlocking(<http://Dispatchers.IO|Dispatchers.IO>)
instead of
runBlocking { }
, but not sure what is the immediate difference. My app is a backend so no main thread but still want to know the difference. Thanks
s
The default dispatcher has some reserved threads that are not supposed to block. The idea is that there are enough of these reserved threads to fully occupy the CPU at all times. If one of those threads became blocked waiting for IO, the CPU cores might be under utilised. Using
<http://Dispatchers.IO|Dispatchers.IO>
basically tells the coroutine not to run on one of those reserved threads.
👍 1
Actually I think the implementation will let you switch from the default dispatcher to the IO dispatcher without actually switching threads. It just ensures there are a sufficient number of threads reserved for CPU tasks. But I find it easier to reason about if I pretend they're two separate thread pools.
a
I see, so that's why in my case
<http://Dispatchers.IO|Dispatchers.IO>
is theoretically better since it generally has a bigger thread pool that are usually for blocking tasks (not using the CPU much). I think the limit by default is 64 for
<http://Dispatchers.IO|Dispatchers.IO>
while
Dispatchers.Default
is 2x the cpu core or something like that. (I say in theory because as you mentioned the doc says they share threads to avoid context switching).
s
👍 the important thing is not to occupy the default dispatcher's threads with tasks that aren't using the CPU
👍 1