are Coroutines suitable for a resource-level-lock ...
# coroutines
j
are Coroutines suitable for a resource-level-lock of some kind? Trying to implement a resource locking system where any of those resources can be modified concurrently, but if that resource is already locked then the Coroutine should suspend until the lock is available. This is what I have so far, but I feel like this is a really naive way of doing things. Any suggestions on how to improve this? I'm managing the Set from a single thread since I'm fairly sure that a MutableSet (LinkedHashSet) is not thread safe
g
I would just use Mutex from coroutines
m
I was about to say the same, but looked for the docs first 😛 Docs are here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/
j
I did look at mutex, but it looked like it was using referential equality for comparing owners, but I don't think i can garantee that
message has been deleted
o
Mutex
also doesn't seem to support read-write locking (owner token is just for debugging and has no effect on actual mechanics from what I see on the docs)
j
i'm also fairly new at concurrency primitives 😞
g
But why do you need owner for your case? Isn't mutex.withLock does exactly what your code in getLock
o
in general locking is usually an anti-pattern with coroutines. but I think if you need to keep this type of structure, using a
ConcurrentHashMap<Long, Mutex>
should be sufficient for your use case. You can remove from the map when you unlock, so basically one of 2 things happens: 1) no lock in map, resource isn't locked 2) lock in map, try to lock it and either a) acquire lock and process or b) suspend until lock is released
❤️ 1
j
I looked more at the documentation for mutex. but that seems to only look like it can lock one resource? they are similar, but what i made is something for locking multiple resources. If i used mutex would i need to something like a Map<Long, Mutex>?
oh nice
o
you'll have to be careful with memory effects in 2.a though
since you will unlock after 2.b, but also remove it from the map (maybe making a fresh lock is the best idea?). that's just an bare bones idea
❤️ 1
j
normally i think that locks are an anti pattern, but i need to essentially perform a transaction or something i'm working on
not really a database thing, but a merkle tree thing involving merging two divergent histories back together, and then rewriting history
or maybe i don't know enough about coroutines to think about it a different way
@octylFractal oh yay, the Mutex also preserves order that they were locked in
g
You can use getOrPut { Mutex() }
o
also
mutex.withLock(action)
j
Thanks guys! @gildor @octylFractal