Is there a way to synchronously check if a Mutex i...
# coroutines
s
Is there a way to synchronously check if a Mutex is unlocked and run a block of code under it? Similar to
Mutex.withLock { ... }
, but with calls while the Mutex is locked being discarded instead of suspending.
o
is
tryLock
not good enough?
if you really want a `tryWithLock`:
Copy code
inline fun <T : Any> Mutex.tryWithLock(owner: Any? = null, action: () -> T): T? {
    return if (tryLock(owner)) {
        try {
            action()
        } finally {
            unlock(owner)
        }
    } else {
        null
    }
}
explicitly forbids
null
because it's the failure signal here, you can change that up if you want
s
My issue with tryLock was that it didn’t immediately run the block, so there was a race condition.
That tryWithLock extension method is what I was thinking about writing, nice!
o
I don't get what the race condition is here? if
tryLock
returns
true
, you got the exclusive lock -- nothing can interrupt it
s
I think I had the synchronous bits mixed up in my head, I was imagining the following at first:
Copy code
if (!mutex.isLocked) {
    mutex.withLock { ... }
}
Looking back at that, I can see the flaw
o
yea, there's a race condition there -- but I think
tryLock
should work
s
👍