Skip to content

Instantly share code, notes, and snippets.

@nmccready
Forked from jeffreyolchovy/LRUCache.scala
Created April 5, 2014 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmccready/9993567 to your computer and use it in GitHub Desktop.
Save nmccready/9993567 to your computer and use it in GitHub Desktop.
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