Skip to content

Instantly share code, notes, and snippets.

@raimohanska
Created December 15, 2011 11:55
Show Gist options
  • Save raimohanska/1480849 to your computer and use it in GitHub Desktop.
Save raimohanska/1480849 to your computer and use it in GitHub Desktop.
My first Scala cache
package com.karma.cache
import collection.immutable.HashMap
trait Cache[K, V] {
def get(key : K, fetch : (K => V)) : V
}
class NoCache[K, V] extends Cache[K, V] {
def get(key : K, fetch : (K => V)) : V = fetch(key)
}
class TTLCache[K, V](ttlMs : Long) extends Cache[K, V] {
private case class Entry(value : V, timestamp : Long = System.currentTimeMillis)
private var data = new HashMap[K, Entry]
private var lastCleanup = System.currentTimeMillis
def get(key : K, fetch : (K => V)) : V = {
cleanup
data.get(key) match {
case Some (Entry(v, ts)) if (isValid(ts)) => v
case None => val v = fetch(key)
data += key -> Entry(v)
v
}
}
private def isValid(timestamp : Long) = {
timestamp >= System.currentTimeMillis - ttlMs
}
private def cleanup {
if (!isValid(lastCleanup)) {
data = data.filter({case (key, entry) => isValid(entry.timestamp)})
lastCleanup = System.currentTimeMillis
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment