Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LRUCache in Scala?

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.

like image 513
pathikrit Avatar asked Jan 28 '13 12:01

pathikrit


2 Answers

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
like image 62
Yuriy Tumakha Avatar answered Sep 21 '22 15:09

Yuriy Tumakha


Found exactly what I was looking in Twitter's Scala Util library

like image 39
pathikrit Avatar answered Sep 20 '22 15:09

pathikrit