Created
August 6, 2012 21:19
-
-
Save jeffreyolchovy/3278505 to your computer and use it in GitHub Desktop.
LRU cache implementation in Scala
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
import akka.stm._ | |
import scala.collection.immutable.ListMap | |
case class LRUCache[A, B](private val MAX_ENTRIES: Int) | |
{ | |
protected val cache = Ref(ListMap.empty[A, B]) | |
def getOrElse(key: A)(fn: => B): B = { | |
get(key).getOrElse { | |
val result = fn | |
put(key, result) | |
result | |
} | |
} | |
def get(key: A): Option[B] = atomic { | |
cache.get.get(key) | |
} | |
def put(key: A, value: B) = atomic { | |
cache.alter { current => | |
val altered = current + (key -> value) | |
if(altered.size > MAX_ENTRIES) altered.takeRight(MAX_ENTRIES) else altered | |
} | |
} | |
def remove(key: A) = atomic { | |
cache.alter { current => current - key } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What are you supposed to do now that akka has dropped stm?
(and twitter dropped util-collections which had an LRUCache implementation.)