Should I use `withContext(<http://Dispatchers.IO|D...
# coroutines
r
Should I use
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
when using
ConcurrentHashMap
inside a suspending function?
d
In general no.
ConcurrentHashMap
is lock-free for retrieval and overall it doesn't make much sense to switch the entire threadpool just to access a map
r
And when inserting something into the map?
d
That depends on if you have multiple concurrent writers. But even then it would only make sense if you really can't block the thread for the miniscule amount of time it takes to acquire the lock, write to the map and unlock again. Note that
withContext
also has a cost, you need to create the other coroutine and schedule it (which will most likely also involve some kind of lock). So in general it does not make much sense, imho. Of course there could be very special use-cases...
­čÖĆ 1
s
Like performing blocking io in
compute
variants ;-)
d
Which is inadvisable anyways, because if I understand correctly that would block the Map for updates for that duration, which is probably not desirable.
k
IIRC, locking might actually slow down your code when you are adding a bunch of new items to the map, as the map tries to use any thread that tries to access the map in helping with copying the data.