如何在scala中缓存结果? [英] How to cache results in scala?

查看:281
本文介绍了如何在scala中缓存结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此页面对地图的 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))
}

因此您可以使用 catchedFun1 将检查 cacheFun1 是否包含与之关联的键和返回值。否则,它将调用 fun1 ,然后将 fun1 的结果缓存在 cacheFun1 ,然后返回 fun1 的结果。

So you can use catchedFun1 which will check if cacheFun1 contains key and return value associated with it. Otherwise, it will invoke fun1, then cache fun1's result in cacheFun1, then return fun1's result.

我看到一个潜在的危险- cacheFun1 可能会变大。因此,必须通过垃圾收集器以某种方式清除 cacheFun1 吗?

I can see one potential danger - cacheFun1 can became to large. So cacheFun1 must be cleaned somehow by garbage collector?

P.S。 scala.collection.mutable.WeakHashMap和java.lang.ref。* 怎么办?

推荐答案

请参见备忘录模式 Scalaz实施

还可以检查STM实现,例如 Akka

Also check out a STM implementation such as Akka.

并非仅是本地缓存,因此您可能希望查找分布式缓存或 STM ,例如 CCSTM Terracotta Hazelcast

Not that this is only local caching so you might want to lookinto a distributed cache or STM such as CCSTM, Terracotta or Hazelcast

这篇关于如何在scala中缓存结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆