Created
December 15, 2011 11:55
-
-
Save raimohanska/1480849 to your computer and use it in GitHub Desktop.
My first Scala cache
This file contains hidden or 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
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