All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.io.dyte.core.ThreadSafeMap.kt Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
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()
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy