LruCache with linkedMapOf

This commit is contained in:
Lev Shagalov 2022-07-15 10:17:42 +03:00
parent 0694cd6a07
commit fc0f223766

View File

@ -6,16 +6,11 @@ import kotlin.jvm.Synchronized
class LruCache<K, V>( class LruCache<K, V>(
private var capacity: Int, private var capacity: Int,
) { ) {
private val cache = linkedMapOf<K, V>()
private val cache = mutableMapOf<K, V>()
private val order = mutableListOf<K>()
@Synchronized @Synchronized
fun getCache() = cache.toMap() fun getCache() = cache.toMap()
@Synchronized
fun getOrder() = order.toList()
@Synchronized @Synchronized
fun put(key: K, value: V) = internalPut(key, value) fun put(key: K, value: V) = internalPut(key, value)
@ -25,7 +20,6 @@ class LruCache<K, V>(
@Synchronized @Synchronized
fun remove(key: K) { fun remove(key: K) {
cache.remove(key) cache.remove(key)
order.remove(key)
} }
@Synchronized @Synchronized
@ -37,25 +31,23 @@ class LruCache<K, V>(
@Synchronized @Synchronized
fun clear(newCapacity: Int? = null) { fun clear(newCapacity: Int? = null) {
cache.clear() cache.clear()
order.clear()
capacity = newCapacity ?: capacity capacity = newCapacity ?: capacity
} }
private fun internalGet(key: K): V? { private fun internalGet(key: K): V? {
val value = cache[key] val value = cache[key]
if (value != null) { if (value != null) {
order.remove(key) cache.remove(key)
order.add(key) cache[key] = value
} }
return value return value
} }
private fun internalPut(key: K, value: V) { private fun internalPut(key: K, value: V) {
if (cache.size >= capacity) { if (cache.size >= capacity) {
cache.remove(order.removeAt(0)) cache.remove(cache.iterator().next().key)
} }
cache[key] = value cache[key] = value
order.add(key)
} }
} }