Skip to content

Instantly share code, notes, and snippets.

@pcejrowski
Created January 10, 2018 13: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 pcejrowski/54f5c388bf5f02481479af2f994f8e2e to your computer and use it in GitHub Desktop.
Save pcejrowski/54f5c388bf5f02481479af2f994f8e2e to your computer and use it in GitHub Desktop.
Simple in-memory cache in Scala
import java.util.concurrent.ConcurrentHashMap
class EternalInMemoryCache[A, B]{
private val underlying = new ConcurrentHashMap[A,B]()
def cached(key: A)(value: => B): B = {
Option(underlying.get(key)) match {
case Some(v) => v
case None =>
underlying.put(key, value)
value
}
}
}
val cache = new EternalInMemoryCache[String, String]
cache.cached("foo"){"bar"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment