KeyedMutex

A keyed, suspend-friendly mutex for Kotlin Multiplatform.

Guarantees mutual exclusion per key, without blocking threads. API mirrors the kotlinx.coroutines Mutex:

  • lock(key, owner)

  • tryLock(key, owner)

  • unlock(key, owner)

  • withLock(key, owner) { ... }

Internals:

  • A per-key entry holds a Mutex and a reference count (holders/waiters).

  • We increment refs before suspending for lock(key) so entries aren’t removed while waiting.

  • Cleanup removes the entry only when refs == 0 and the mutex is not locked.

Constructors

Link copied to clipboard
constructor()

Functions

Link copied to clipboard
suspend fun holdsLock(key: K, owner: Any): Boolean

Checks whether this key is locked by the specified owner.

Link copied to clipboard
suspend fun isLocked(key: K): Boolean

Optional: observe whether a key appears locked. For diagnostics/metrics only (not a synchronization primitive).

Link copied to clipboard
suspend fun lock(key: K, owner: Any? = null)

Suspends until the lock for key is acquired. Not re-entrant for the same key within the same coroutine.

Link copied to clipboard
suspend fun tryLock(key: K, owner: Any? = null): Boolean

Attempts to acquire the lock for key without suspension. Returns true if a lock was acquired.

Link copied to clipboard
suspend fun unlock(key: K, owner: Any? = null)

Releases the lock for key. Must be called exactly once per successful lock/tryLock.

Link copied to clipboard
inline suspend fun <K, T> KeyedMutex<K>.withLock(key: K, owner: Any? = null, action: suspend () -> T): T

Convenience function mirroring Mutex.withLock