commonMain.io.dyte.core.ThreadSafeMap.kt Maven / Gradle / Ivy
package io.dyte.core
import kotlinx.coroutines.*
internal class ThreadSafeMap {
private val map: MutableMap = mutableMapOf()
@OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)
private val serialScope =
CoroutineScope(
newSingleThreadContext("synchronizationPool")
) // We want our code to run on 4 threads
operator fun get(key: Key): Value? {
return runBlocking { serialScope.async { map[key] }.await() }
}
operator fun set(key: Key, value: Value) {
serialScope.launch { map[key] = value }
}
fun getOrElse(key: Key, execute: () -> Value): Value {
val result = get(key)
if (result != null) {
return result
}
return execute()
}
fun remove(key: Key): Value? {
return runBlocking { serialScope.async { map.remove(key) }.await() }
}
fun getValue(key: Key): Value {
return get(key) ?: throw NoSuchElementException()
}
}