-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Switch to thread safe regex match caching (#4)
- Loading branch information
Showing
2 changed files
with
57 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
syntakts-core/src/commonMain/kotlin/xyz/wingio/syntakts/util/SynchronizedCache.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package xyz.wingio.syntakts.util | ||
|
||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.sync.Mutex | ||
import kotlinx.coroutines.sync.withLock | ||
|
||
/** | ||
* Thread safe cache store, all writes are restricted with a [Mutex] to prevent [ConcurrentModificationException]s | ||
*/ | ||
public class SynchronizedCache<K, V> { | ||
|
||
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Main.immediate) | ||
private val mutex: Mutex = Mutex(false) | ||
private val cache: MutableMap<K, V?> = mutableMapOf() | ||
|
||
/** | ||
* Number of cached entities | ||
*/ | ||
public val size: Int get() = cache.size | ||
|
||
public operator fun set(key: K, value: V?) { | ||
scope.launch { | ||
mutex.withLock { | ||
cache[key] = value | ||
} | ||
} | ||
} | ||
|
||
public operator fun get(key: K): V? { | ||
return cache[key] | ||
} | ||
|
||
/** | ||
* Returns true if this cache already contains an element with the given [key] | ||
*/ | ||
public fun hasKey(key: K): Boolean { | ||
return cache.containsKey(key) | ||
} | ||
|
||
/** | ||
* Removes the first element of this cache | ||
*/ | ||
public fun removeFirst() { | ||
scope.launch { | ||
mutex.withLock { | ||
cache.remove(cache.keys.firstOrNull()) | ||
} | ||
} | ||
} | ||
|
||
} |