Skip to content

Commit

Permalink
Add LruCache, a cache implementation using LRU algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
alialbaali committed Jan 24, 2021
1 parent 0eda67f commit 42893bb
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/main/kotlin/io/kamel/core/cache/LruCache.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package io.kamel.core.cache

private const val LoadFactor = 0.75F

/**
* Cache implementation which evicts items using an LRU algorithm.
*/
internal class LruCache<K, V>(override val maxSize: Int) : Cache<K, V> {

private val cache: MutableMap<K, V> = object : LinkedHashMap<K, V>(maxSize, LoadFactor, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<K, V>?): Boolean = size > maxSize
}

override val size: Int
get() = cache.size

init {
require(maxSize >= 0) { "Cache max size must be positive number" }
}

override fun get(key: K): V? = cache[key]

override fun set(key: K, value: V) = cache.set(key, value)

override fun remove(key: K): Boolean = cache.remove(key) != null

override fun clear(): Unit = cache.clear()

}

0 comments on commit 42893bb

Please sign in to comment.