KeyedMutex

class KeyedMutex<K>

A map of independent mutexes keyed by K, with mutual exclusion per key.

Two callers using different keys never block each other; two callers using equal keys serialize. Keys need stable equals and hashCode. Entries are created on demand and removed as soon as the last interested caller leaves, so unused keys hold no memory.

Thread safety: this class is safe for concurrent use from multiple coroutines and threads; all internal state is guarded by a Mutex.

Constructors

Link copied to clipboard
constructor()

Functions

Link copied to clipboard
suspend fun activeKeyCount(): Int

Returns the number of keys currently tracked by this instance.

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

Returns true while some caller holds the mutex for key.

Link copied to clipboard
suspend fun <T> withLock(key: K, block: suspend () -> T): T

Runs block while holding the mutex for key.

Link copied to clipboard
suspend fun <T> withLockOrNull(key: K, timeout: Duration, block: suspend () -> T): T?

Runs block while holding the mutex for key, waiting at most timeout, returning null on timeout.