If some code does (de)serialization or other potentially CPU-intensive work like using a template system to build HTML (all in-memory), do you do delegate the execution to the
Default
dispatcher? Or do you you accept that the current dispatcher (whatever it is) is potentially blocked for a few milliseconds?
I have the habit of wrapping such code in
withContext(Dispatchers.Default) { … }
, but I’m not actually sure if that’s necessary. Or maybe it’s even a bad idea.
k
krzysztof
01/26/2021, 4:33 PM
Why would you think it’s a bad idea? I say that’s a good habit to have, since you don’t want to block whatever thread you’re on. What if your suspend function is redirected to
main
dispatcher? It’d mean you’ll block UI, if you don’t change the thread
☝️ 2
m
Marc Knaup
01/26/2021, 4:35 PM
Switching dispatchers also doesn’t come free. But I guess it’s negligible compared to serialization/templating work.
But yeah, makes sense for
Main
dispatchers. I mostly have such cases in back-end where I don’t use
Main
.
c
christophsturm
01/26/2021, 4:39 PM
i think its also important in the backend, and can severly affect concurrency if you block your non blocking io thread too long
l
louiscad
01/27/2021, 8:11 PM
Switching between IO and Default is almost free, you just pay the lambda, but the threads don't switch, the same thread switches dispatcher seamlessly.
u
uli
01/28/2021, 2:41 PM
Do add to @louiscad if you are only using the 3 pre-existing dispatcher (Default,Main,IO), thread switching is only involved if you were initially on the main dispatcher. And that’s when you need it.
If you are currently dispatched on IO or Default dispatcher withContext(Dispatcher.Default) should keep execution on the same thread and therefor be almost free.
k
krzysztof
01/28/2021, 2:45 PM
Interesting - is this behavior documented somewhere?