How to cache the results in scala?
source link: https://www.codesd.com/item/how-to-cache-the-results-in-scala.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to cache the results in scala?
This page has a description of Map's getOrElseUpdate
usage method:
object WithCache{
val cacheFun1 = collection.mutable.Map[Int, Int]()
def fun1(i:Int) = i*i
def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i))
}
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.
I can see one potential danger - cacheFun1
can became to large. So cacheFun1
must be cleaned somehow by garbage collector?
P.S. What about scala.collection.mutable.WeakHashMap and java.lang.ref.*
?
See the Memo pattern and the Scalaz implementation of said paper.
Also check out a STM implementation such as Akka.
Not that this is only local caching so you might want to lookinto a distributed cache or STM such as CCSTM, Terracotta or Hazelcast
Related Articles
How to cache the results of a Spring Data JPA query method without using the query cache?
How to cache the results
How to cache the results of a WCF service call
Haskell Caches the Results of a Function
How to store the result of an action in an apache spark using scala
How to stop the results of a cached jquery php load
How do I cache the result of the API call?
Which is better: Analyze the big data every time from the database or cache the result?
Retrieving and caching the result in Select2
How to get the result of the select statement grouped by a column to perform a join statement on it?
How to display the results from the search field in the main page in asp.net
Caching the result of all methods
Dynamic sql, how to save the result query in a new table?
How to interpret the result of the Weka J48 classification
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK