I know Guava has an excellent caching library but I am looking for something more Scala/functional friendly where I can do things like cache.getOrElse(query, { /* expensive operation */})
. I also looked at Scalaz's Memo but that does not have lru expiration.
LRUCache solution based on Java LinkedHashMap and exposed as Scala mutable.Map
import java.util.Collections.synchronizedMap
import scala.collection.JavaConversions._
import scala.collection.mutable
class LRUCache[K, V](maxEntries: Int)
extends java.util.LinkedHashMap[K, V](100, .75f, true) {
override def removeEldestEntry(eldest: java.util.Map.Entry[K, V]): Boolean
= size > maxEntries
}
object LRUCache {
def apply[K, V](maxEntries: Int): mutable.Map[K, V]
= synchronizedMap(new LRUCache[K, V](maxEntries))
}
When map size > maxEntries last recent used entry will be removed.
LinkedHashMap 3rd constructor parameter should be set as true for LRU strategy.
LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)
Usage example:
val cache = LRUCache[String, Int](1000)
val key = "key1"
val value = 111
cache.get(key) shouldBe None
cache += key -> value
cache.get(key) shouldBe Some(value)
cache(key) shouldBe value
Found exactly what I was looking in Twitter's Scala Util library
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With