Skip to content

Instantly share code, notes, and snippets.

@kareblak
Last active August 29, 2015 14:06
Show Gist options
  • Save kareblak/6314faf4ffea57842943 to your computer and use it in GitHub Desktop.
Save kareblak/6314faf4ffea57842943 to your computer and use it in GitHub Desktop.
case class GetOrElseCachedValue[K, V](key: K, orElse: () => V)
case class GetCachedValue[K, V](key: K)
case class PutCachedValue[K, V](key: K, value: V)
case class ReturnCachedValue[V](value: Option[V])
case class RemoveCachedValue[K](key: K)
case object PurgeCachedValues
class CacheActor[K, V] private[cache](cache: Cache) extends Actor with ActorLogging with StatsD {
type FV = (() => V)
def receive = {
case GetOrElseCachedValue(key: K, orElse: FV) =>
sender ! ReturnCachedValue(get(key, orElse))
case GetCachedValue(key: K) =>
sender ! ReturnCachedValue(get(key))
case PutCachedValue(key: K, value: FV) =>
put(key, value)
case RemoveCachedValue(key: K) =>
remove(key)
case PurgeCachedValues =>
purge()
}
...
def get(key: K, orElse: FV): Option[V] = {
get(key).orElse {
Option(orElse()).map { value =>
val element = new Element(key, value)
cache.put(element)
value
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment