Refine NamedMutex

This commit is contained in:
Dude so hot authored and renovate[bot] committed 2024-10-19 21:36:40 +08:00
1 parent 447a31ea00
commit 6aba1670ec
1 file changed
+7 -9
@@ -5,18 +5,17 @@ import io.ktor.utils.io.pool.DefaultPool
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class MutexTracker(val mutex: Mutex = Mutex(), var count: Int = 0) {
class MutexTracker(mutex: Mutex = Mutex(), private var count: Int = 0) : Mutex by mutex {
operator fun inc() = apply { count++ }
operator fun dec() = apply { count-- }
val isFree
get() = count == 0
}
val MutexTracker.isFree
get() = count == 0
class MutexPool(capacity: Int) : DefaultPool<MutexTracker>(capacity) {
override fun produceInstance() = MutexTracker()
override fun validateInstance(mutex: MutexTracker) {
check(!mutex.mutex.isLocked)
check(!mutex.isLocked)
check(mutex.isFree)
}
}
@@ -24,15 +23,14 @@ class MutexPool(capacity: Int) : DefaultPool<MutexTracker>(capacity) {
class NamedMutex<K>(capacity: Int) {
val pool = MutexPool(capacity)
val active = mutableScatterMapOf<K, MutexTracker>()
val lock = Any()
}
suspend inline fun <K, R> NamedMutex<K>.withLock(key: K, owner: Any? = null, action: () -> R): R {
val mutex = synchronized(lock) { active.getOrPut(key) { pool.borrow() }.inc() }
val mutex = synchronized(active) { active.getOrPut(key) { pool.borrow() }.inc() }
return try {
mutex.mutex.withLock(owner, action)
mutex.withLock(owner, action)
} finally {
synchronized(lock) {
synchronized(active) {
mutex.dec()
if (mutex.isFree) {
active.remove(key)