Skip to content

Add Mutex.holdsLock #92

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ public interface Mutex {
public fun <R> registerSelectLock(select: SelectInstance<R>, owner: Any?, block: suspend () -> R)

/**
* Checks mutex locked by owner
*
* @return `true` on mutex lock by owner, `false` if not locker or it is locked by different owner
*/
public fun holdsLock(owner: Any): Boolean

/**
* Unlocks this mutex. Throws [IllegalStateException] if invoked on a mutex that is not locked.
*
* @param owner Optional owner token for debugging. When `owner` is specified (non-null value) and this mutex
Expand Down Expand Up @@ -339,6 +346,15 @@ internal class MutexImpl(locked: Boolean) : Mutex {
}
}

public override fun holdsLock(owner: Any) =
_state.let { state ->
when (state) {
is Empty -> state.locked === owner
is LockedQueue -> state.owner === owner
else -> false
}
}

public override fun unlock(owner: Any?) {
while (true) { // lock-free loop on state
val state = this._state
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,37 @@ class MutexTest : TestBase() {
mutex.unlock() // should not produce StackOverflowError
assertThat(done, IsEqual(waiters))
}

@Test
fun holdLock() = runBlocking {
val mutex = Mutex()
val firstOwner = Any()
val secondOwner = Any()

// no lock
assertFalse(mutex.holdsLock(firstOwner))
assertFalse(mutex.holdsLock(secondOwner))

// owner firstOwner
mutex.lock(firstOwner)
val secondLockJob = launch(CommonPool) {
mutex.lock(secondOwner)
}

assertTrue(mutex.holdsLock(firstOwner))
assertFalse(mutex.holdsLock(secondOwner))

// owner secondOwner
mutex.unlock(firstOwner)
secondLockJob.join()

assertFalse(mutex.holdsLock(firstOwner))
assertTrue(mutex.holdsLock(secondOwner))

mutex.unlock(secondOwner)

// no lock
assertFalse(mutex.holdsLock(firstOwner))
assertFalse(mutex.holdsLock(secondOwner))
}
}