File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
kotlinx-coroutines-core/src
main/kotlin/kotlinx/coroutines/experimental/sync
test/kotlin/kotlinx/coroutines/experimental/sync Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -91,6 +91,13 @@ public interface Mutex {
91
91
public fun <R > registerSelectLock (select : SelectInstance <R >, owner : Any? , block : suspend () -> R )
92
92
93
93
/* *
94
+ * Checks mutex locked by owner
95
+ *
96
+ * @return `true` on mutex lock by owner, `false` if not locker or it is locked by different owner
97
+ */
98
+ public fun holdsLock (owner : Any ): Boolean
99
+
100
+ /* *
94
101
* Unlocks this mutex. Throws [IllegalStateException] if invoked on a mutex that is not locked.
95
102
*
96
103
* @param owner Optional owner token for debugging. When `owner` is specified (non-null value) and this mutex
@@ -325,6 +332,15 @@ internal class MutexImpl(locked: Boolean) : Mutex {
325
332
}
326
333
}
327
334
335
+ public override fun holdsLock (owner : Any ) =
336
+ _state .value.let { state ->
337
+ when (state) {
338
+ is Empty -> state.locked == = owner
339
+ is LockedQueue -> state.owner == = owner
340
+ else -> false
341
+ }
342
+ }
343
+
328
344
public override fun unlock (owner : Any? ) {
329
345
_state .loop { state ->
330
346
when (state) {
Original file line number Diff line number Diff line change @@ -107,4 +107,37 @@ class MutexTest : TestBase() {
107
107
mutex.unlock() // should not produce StackOverflowError
108
108
assertThat(done, IsEqual (waiters))
109
109
}
110
+
111
+ @Test
112
+ fun holdLock () = runBlocking {
113
+ val mutex = Mutex ()
114
+ val firstOwner = Any ()
115
+ val secondOwner = Any ()
116
+
117
+ // no lock
118
+ assertFalse(mutex.holdsLock(firstOwner))
119
+ assertFalse(mutex.holdsLock(secondOwner))
120
+
121
+ // owner firstOwner
122
+ mutex.lock(firstOwner)
123
+ val secondLockJob = launch(CommonPool ) {
124
+ mutex.lock(secondOwner)
125
+ }
126
+
127
+ assertTrue(mutex.holdsLock(firstOwner))
128
+ assertFalse(mutex.holdsLock(secondOwner))
129
+
130
+ // owner secondOwner
131
+ mutex.unlock(firstOwner)
132
+ secondLockJob.join()
133
+
134
+ assertFalse(mutex.holdsLock(firstOwner))
135
+ assertTrue(mutex.holdsLock(secondOwner))
136
+
137
+ mutex.unlock(secondOwner)
138
+
139
+ // no lock
140
+ assertFalse(mutex.holdsLock(firstOwner))
141
+ assertFalse(mutex.holdsLock(secondOwner))
142
+ }
110
143
}
You can’t perform that action at this time.
0 commit comments