https://kotlinlang.org logo
Title
r

Robert Jaros

02/18/2020, 1:59 PM
Should I use
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { }
when using
ConcurrentHashMap
inside a suspending function?
d

diesieben07

02/18/2020, 2:01 PM
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

Robert Jaros

02/18/2020, 2:07 PM
And when inserting something into the map?
d

diesieben07

02/18/2020, 2:09 PM
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...
:tnx: 1
s

spand

02/18/2020, 2:18 PM
Like performing blocking io in
compute
variants ;-)
d

diesieben07

02/18/2020, 2:19 PM
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

Kroppeb

02/18/2020, 8:23 PM
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.