Mutex

interface Mutex (source)

Platform and version requirements: JVM

Mutual exclusion for coroutines.

Mutex has two states: locked and unlocked. It is non-reentrant, that is invoking lock even from the same thread/coroutine that currently holds the lock still suspends the invoker.

Properties

isLocked

abstract val isLocked: Boolean

Returns true when this mutex is locked.

onLock

abstract val onLock: SelectClause2<Any?, Mutex>

Clause for select expression of lock suspending function that selects when the mutex is locked. Additional parameter for the clause in the owner (see lock) and when the clause is selected the reference to this mutex is passed into the corresponding block.

Functions

holdsLock

abstract fun holdsLock(owner: Any): Boolean

Checks mutex locked by owner

lock

abstract suspend fun lock(owner: Any? = null): Unit

Locks this mutex, suspending caller while the mutex is locked.

tryLock

abstract fun tryLock(owner: Any? = null): Boolean

Tries to lock this mutex, returning false if this mutex is already locked.

unlock

abstract fun unlock(owner: Any? = null): Unit

Unlocks this mutex. Throws IllegalStateException if invoked on a mutex that is not locked.

Extension Functions

withLock

suspend fun <T> Mutex.withLock(
    owner: Any? = null,
    action: () -> T
): T

Executes the given action under this mutex’s lock.