forked from Kotlin/kotlinx.coroutines
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPermitTransfer.jvm.kt
35 lines (31 loc) · 999 Bytes
/
PermitTransfer.jvm.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package kotlinx.coroutines.internal
import java.util.concurrent.locks.*
internal actual class PermitTransfer {
private val status = PermitTransferStatus()
public actual fun releaseFun(releasePermit: () -> Unit): () -> Unit {
val blockedThread = Thread.currentThread()
return {
if (status.complete()) {
try {
releasePermit()
} finally {
LockSupport.unpark(blockedThread)
}
}
}
}
public actual fun acquire(tryAllocatePermit: () -> Boolean, deallocatePermit: () -> Unit) {
while (true) {
if (status.check()) {
return
}
if (tryAllocatePermit()) {
if (!status.complete()) { // race: transfer was completed first by releaseFun
deallocatePermit()
}
return
}
LockSupport.park(this)
}
}
}