I have a map that is going to be used by multiple ...
# coroutines
l
I have a map that is going to be used by multiple coroutines; its entries will be read and modified. How to make sure this map is thread-safe? I came across mutex and atomics but I'm not sure what's the difference between them. I know
Mutex
uses atomics internally too and that made me more confused. I also don't fully understand how atomics work in the first place, like in what case would they lock the object? Would putting my map in an atomic guarantees the operations performed will be synchronized? etc
o
if it's just JVM, use
ConcurrentHashMap
, otherwise just wrap the
Mutex
around each call to the map, like a
synchronizedMap
does. Alternatively, set up a single "owning" coroutine actor, that reads from a Channel. The Channel will hold messages telling it either to write to the map or read a value into a CompletableDeferred, and since the actor is the only one using the map, it doesn't need any thread-safety.
l
It's multiplatform (we support jvm and native) so I need a solution that would work for all of them similarly. I heard mutex is slow so i'm trying to avoid it
I'm just trying to gain an understanding of the options (confining to a thread/coroutine, mutex, atomics), how they work and which one would be faster for my case
o
so it's basically just the difference between blocking and suspending. blocking means that the whole Thread is essentially taken up by the code, nothing else can execute on the Thread (which is bad, since then you need another heavy Thread to do concurrent work). suspending is the same, but replacing Thread with Coroutine. and since when coroutines suspend they are removed from their "host" Thread, the Thread can be re-used to run other Coroutines that aren't suspending. Mutex is the suspending version of Lock, all atomics are blocking and there's not really a replacement for them in suspending code, since atomics are tied to CPU instructions, not a high-level language feature.
l
ah, thank you so much
u
On native and Js you don't need thread safety as you are running your curoutines on a single thread. So expected hashmao can have concurrent hashmap as actual on jvn and regular hashmap on other platforms
l
native can't have multiple threads?
u
It can. But it can not easily share memory between threads
l
i see, that's interesting
As a consequence curoutines do not support dispatching to other threads on native
j
depending on the size of the map and scope of changes, small arrays and COWArrayList may be interesting lockless alternatives to syncronous maps.
if you pursue eventual consistency instead of ACID then lockless options can reduce hardware overheads and change read-write transaction costs. these tend to focus on doing operations on small arrays to take advantage of CPU cache affinity
254 Views