此页面描述了Map的getOrElseUpdate使用方法:
object WithCache{
val cacheFun1 = collection.mutable.Map[Int, Int]()
def fun1(i:Int) = i*i
def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i))
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以使用catchedFun1哪个将检查是否cacheFun1包含与之关联的键和返回值.否则,它将调用fun1,然后缓存fun1结果cacheFun1,然后返回fun1结果.
我可以看到一个潜在的危险 - cacheFun1可能变得很大.所以cacheFun1必须通过垃圾收集器以某种方式清理?
PS怎么样scala.collection.mutable.WeakHashMap and java.lang.ref.* ?
看看喷雾缓存(超级简单易用)
http://spray.io/documentation/1.1-SNAPSHOT/spray-caching/
使工作变得轻松,并具有一些很好的功能
例如 :
import spray.caching.{LruCache, Cache}
//this is using Play for a controller example getting something from a user and caching it
object CacheExampleWithPlay extends Controller{
//this will actually create a ExpiringLruCache and hold data for 48 hours
val myCache: Cache[String] = LruCache(timeToLive = new FiniteDuration(48, HOURS))
def putSomeThingInTheCache(@PathParam("getSomeThing") someThing: String) = Action {
//put received data from the user in the cache
myCache(someThing, () => future(someThing))
Ok(someThing)
}
def checkIfSomeThingInTheCache(@PathParam("checkSomeThing") someThing: String) = Action {
if (myCache.get(someThing).isDefined)
Ok(s"just $someThing found this in the cache")
else
NotFound(s"$someThing NOT found this in the cache")
}
}
Run Code Online (Sandbox Code Playgroud)