Skip to content

Instantly share code, notes, and snippets.

@jenglert
Created June 23, 2014 18:07
Show Gist options
  • Save jenglert/9d99706d0d1d4ba79a5f to your computer and use it in GitHub Desktop.
Save jenglert/9d99706d0d1d4ba79a5f to your computer and use it in GitHub Desktop.
import java.util.Date
/**
* Usage:
*
* val someFun: String = SimpleCache({ () => somethingExpensive }, 15.minutes).cachedFun
*
* val theValue = someFun()
*/
class SimpleCache[T](
fun: () => T,
cacheTimeInMs: Long
) {
private var lastUpdated: Date = new Date(0l)
private var entry: Option[T] = None
def cachedFun: () => T = {
if (entry.isDefined &&
(System.currentTimeMillis() - lastUpdated.getTime() < cacheTimeInMs)) {
entry.get _
} else {
val result = fun()
lastUpdated = new Date
entry = Some(result)
entry.get _
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment