Skip to content

Instantly share code, notes, and snippets.

@kirked
Created June 19, 2017 22:36
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 kirked/e7633e536aea20fe3656e797f0feaf2c to your computer and use it in GitHub Desktop.
Save kirked/e7633e536aea20fe3656e797f0feaf2c to your computer and use it in GitHub Desktop.
Temporal Cache
package actors
import akka.actor.{Actor, ActorLogging, Props}
import java.time.Instant
import scala.collection.immutable.TreeMap
import scala.concurrent.duration._
object TemporalCache extends ActorGenerator1[TemporalCache, FiniteDuration] {
def props(checkExpiration: FiniteDuration = 60.seconds) =
Props(new TemporalCache(checkExpiration))
case class Put(key: String, item: AnyRef, expiration: Instant)
case class Get(key: String)
case class Remove(key: String)
case object NotFound
case class Found(key: String, item: AnyRef)
}
class TemporalCache(checkExpiration: FiniteDuration)
extends Actor
with ActorLogging {
import TemporalCache._
import context.dispatcher
case object Expiry
context.system.scheduler.schedule(checkExpiration, checkExpiration, self, Expiry)
var cache = Map.empty[String, AnyRef]
var queue = TreeMap.empty[Instant, String]
def receive = {
case Put(key, item, expiration) =>
cache = cache + (key -> item)
queue = queue + (expiration -> key)
case Get(key) =>
cache.get(key) match {
case Some(item) => sender ! Found(key, item)
case None => sender ! NotFound
}
case Remove(key) =>
cache = cache - key
case Expiry =>
val now = Instant.now
val (queueKeys, cacheKeys) =
queue.takeWhile { case (expires, _) => expires isBefore now }.unzip
if (queueKeys.nonEmpty) {
queue = queue -- queueKeys
cache = cache -- cacheKeys
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment