Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map based cache with expiration and soft values

I'm looking to cache information in a Map so I don't have to keep, for example, hitting a DB. In Java I'd use Google collection's excellent MapMaker and set an expiry, to keep the cache as fresh as necessary, and softValues, to keep the memory usage down. Then I'd have a function that computes the value for a key that currently isn't cached.

MapMaker().softValues
          .expireAfterWrite(10, TimeUnit.MINUTES)
          .makeComputingMap(Function(...));

What's the best way to do this in Scala?

like image 320
Ben Smith Avatar asked Jul 27 '11 13:07

Ben Smith


2 Answers

As Kim said, why do it differently if MapMaker works well for you?

import collection.JavaConverters._
val cache = /* your MapMaker code creating a Java map */.asScala

And now you access the underlying Java map with the methods from a Scala map.

like image 84
Jean-Philippe Pellet Avatar answered Sep 28 '22 20:09

Jean-Philippe Pellet


I have created a functionally transparent expiration map in Scala. Adding and removing elements gives a new map, which also removes any expired values.

Expiration Map

like image 24
J Pullar Avatar answered Sep 28 '22 20:09

J Pullar