-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add LruCache, a cache implementation using LRU algorithm
- Loading branch information
1 parent
0eda67f
commit 42893bb
Showing
1 changed file
with
29 additions
and
0 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
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() | ||
|
||
} |