https://kotlinlang.org logo
Title
a

agu

10/07/2020, 8:45 PM
Hi I'm wondering what are the benefits of using
<http://Dispatchers.IO|Dispatchers.IO>
instead of creating a custom
Executor.asCoroutineDispatcher
, supposing that I'm executing IO operations (http calls)
z

Zach Klippenstein (he/him) [MOD]

10/07/2020, 8:53 PM
Two of the main advantages are: 1) Re-using existing thread pool. All coroutines running on
<http://Dispatchers.IO|Dispatchers.IO>
share a thread pool, even if they’re in different libraries. 2) Sharing threads with other dispatchers.
Dispatchers.Default
and
<http://Dispatchers.IO|Dispatchers.IO>
actually coordinate, so if a coroutine running on Default switches context to IO, the dispatcher will actually just mark the current thread as an IO thread and the coroutine will not need to do an expensive context switch to a different thread to keep running. Some other reasons: - Less code/simpler. Dispatchers.IO is already there, so you don’t have to manage an
Executor
and convert it to a dispatcher yourself. - Communicates intent: If someone is looking at some code and sees it uses the IO dispatcher, it’s clear that the code is intended to make blocking IO calls. If I was looking at a codebase and saw a custom dispatcher, I’d need to go and figure out why, is it special somehow, etc.
👍 9
a

agu

10/07/2020, 9:47 PM
Thank you very much!
r

renatomrcosta

10/08/2020, 7:46 AM
Zachkipp’s reply is fantastic, but I wanted to add a small tidbit on why sometimes it could be useful to create the Executor for yourself. If you are in a situation where a service call can be slow or potentially hog all 64 threads of the IO dispatchers under heavy load, it may make sense for you to dimension your coroutine dispatcher, so that one slow downstream service / public api does not degrate the entirety of your service under load.
👍 1