Is there any way to wait for a `Mutex` to unlock w...
# coroutines
k
Is there any way to wait for a
Mutex
to unlock without acquiring the lock?
I am suspicious that what I’m reaching for is a reader-writer lock https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock
Which appears to be something that’s long been desired. https://github.com/Kotlin/kotlinx.coroutines/issues/94
t
I suspect there is a problem with simply waiting for a Mutex to unlock. It might unlock, but immediately re-lock. So even if you suspended until it unlocked, there is no guarantee it stays unlocked while your code is executing.
☝️ 1
g
Curious about your use case
k
My use case is I want to allow concurrent reads, but exclusive writes to an authorization token that's appended to every single one of my http requests.
g
Yeah, makes sense. Is it for MPP?
k
Yup. It’s done in an apollo interceptor but could conceptually be done from any http interceptor like thing
g
Because for JVM I would probably just use ReadWriteLock, yes it will block, but if there is no write pressure (which is probably the case), it would be negligible
k
This is common code and consumed in K/N
g
Yeah, JVM and JS is easy, Native could be a problem
In general probably using MutableStateFlow be enough for this, it's safe and doesn't block on reading
k
I don’t think it would be for my cause, because when an auth token is expired we try to reauthenticate. Upon doing so we only want to issue one “winner” reauth call, all of the other concurrent ones end up being no-ops. I don’t see an easy way to do that with MSF
g
Ah, I see, makes awnae
Forgot about need for suspend
k
I suppose maybe I could have a writer lock around the MSF but that seems silly
g
Yeah, it doesn't look necessary
I would probably just do with mutex and conditional logic (so to check if it lcoked), it should be sufficient, even if not absolutely correct
k
Our auth stack is fairly sensitive and has been the source of lots of prod issues. I’m not very comfortable with mostly correct at this point
Last week it caused a DDOS of our backend service because of an promotional event which drove lots of traffic. Improper locking in part caused unnecessary reauth calls and made our BE fall over
g
Yes, I understand, but isn't it in the worst case just sending one additional non-authorized request? It's anyway a matter of milliseconds
Don't get me wrong, not claiming that know the best answer, more like trying to brainstorm it
k
Ah I see
I appreciate your brainstorming here
I might take their suggestion for a RW mutex built atop semaphores and use that until coroutines has a first party one
u
One more hint here. Why not implement your own? There are two algorithms found in wikipedia Both look pretty straight forward.
k
Yup that’s the plan!
👍 1
🙂 1
411 Views