Would you convert a ThreadPoolExecutor to coroutin...
# coroutines
p
Would you convert a ThreadPoolExecutor to coroutines? (if with conditions, can you specify, when?)
j
If the project is full Kotlin I would probably do this. I somehow never use threads directly anymore
p
So should I not worry about something not suspending, which in fact should be in any third-party library?
s
Very little reason to do so. The Coroutines library already has the appropriate Dispatchers, and control over them, to satisfy most situations But if you already have one (through some other 3rd party library), yes, then I would convert them
j
> should I not worry about something not suspending, which in fact should be in any third-party library? I don't believe it would be a problem in this case. If you keep your
ThreadPoolExecutor
and expose it as a coroutine dispatcher using
ExecutorService.asCoroutineDispatcher()
, launching coroutines with this dispatcher will have the same effect (in terms of blocked threads) as launching tasks in the original thread pool executor (assuming the contents of these coroutines is the same blocking code as in the tasks). On the other hand, launching coroutines instead of submitting runnables to the executor allows you to gradually introduce actual suspending functions in the tasks and benefit from more interlacing.
If you end up with well-behaved coroutines, you might not need a dedicated thread pool anymore, and can probably switch to the built-in `Dispatchers.IO`/`Dispatchers.Default` depending on the workload
t
one thing i will point out about the built-in dispatchers: it's really painful to get metrics out of them. If you have metrics on your thread pools - things like idle times, average duration, etc - you may want to keep it because otherwise you lose that visibility. if you want both, using the executor as the coroutine dispatcher would give you a bit of both worlds
j
Fair enough. In case it wasn't clear, I'm not necessarily advocating for or against built-in dispatchers or custom pools, but I definitely recommend wrapping any custom
ExecutorService
as dispatchers to use it via coroutines
👍 1