Hey! I am working with Redisson locks and Kotlin c...
# coroutines
g
Hey! I am working with Redisson locks and Kotlin coroutines. The issue is that the locks are based and acquired by a thread (with its thread id), however considering different coroutines can actually be scheduled on the same thread the lock mechanism won’t work across different coroutines (cause they have the same thread id). Do you have any idea on how I could fix this ? Is there a way to have a coroutine id for example ? Thanks
e
Kotlin coroutines can be scheduled on different physical threads, so RLock doesn't seem safe to use - it requires unlock to happen on the same thread as lock
g
You’re right, it’s why I use the forceUnlock which doesn’t cause any problem in my case. But is there any distributed lock library available working with coroutines or a way to adapt Redisson to do as such ?
d
I do not understand the issue. I have ben using redison for 2 years with coroutine. Thread locking works fine (although overkill) for coroutines as long as you dont end up starving the dispatcher by blocking the thread. Is that the issue ? For thread safety, all coroutines on the same thread run synchronously and only are dispatched when crossing a suspend boundry. If your lock is supposed to lock out coroutines on the same thread, then that cant be directly implemented with a shared distributed lock. Depending on your use case, you could use the coroutine mutex to first aquire a coroutine lock then use redision to aquire the shared lock.
If you use a non-sharable-non-reentrant locking primative like Semaphore it should work fine with any number of coroutines on the same thread. Alternatively you can do your own thread management using a single thread dispatcher. depends what your trying to 'lock' from what
e
if you did
Copy code
launch { lock(); suspend(); unlock() }
launch { lock(); suspend(); unlock() }
both of
suspend()
may run concurrently because
lock()
is reentrant and allows the same thread to freely re-acquire a lock that is already owned by it
and what I mentioned is that
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { lock(); suspend(); unlock() }
may resume on a different Java thread, which is also a problem for reentrant mutexes as they keep track of the owning thread
333 Views