Created
May 22, 2018 10:39
-
-
Save JoolsF/e5901ad4bfbd2238e8a73cfb6893f358 to your computer and use it in GitHub Desktop.
Simple cache example 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.joda.time.LocalDateTime | |
| import scala.concurrent.{ExecutionContext, Future} | |
| /** | |
| * Very simple thread-safe cache implementation with basic support for cache invalidation | |
| */ | |
| class TimedCache[K, V](private val store: scala.collection.concurrent.Map[K, (V, LocalDateTime)], | |
| daysCacheValidFor: Int) { | |
| require(daysCacheValidFor >= 1) | |
| /** If given key is already in this map, returns associated value. | |
| * | |
| * Otherwise, computes value from given expression `op`, stores with key | |
| * in map and returns that value. | |
| * | |
| * Concurrent map implementations may evaluate the expression `op` | |
| * multiple times, or may evaluate `op` without inserting the result. | |
| * | |
| * @param key the key to test | |
| * @param op the computation yielding the value to associate with `key`, if | |
| * `key` is previously unbound. | |
| * @return the value associated with key (either previously or as a result | |
| * of executing the method). | |
| */ | |
| def getOrElseUpdate[E](key: K)(op: => Future[V])(implicit ec: ExecutionContext): Future[V] = | |
| store.get(key) match { | |
| case Some(v) if valueNotExpired(v._2) => Future.successful(v._1) | |
| case _ => op.map { v => | |
| val value = (v, LocalDateTime.now()) | |
| store.put(key, value) | |
| v | |
| } | |
| } | |
| def get(k: K): Option[(V, LocalDateTime)] = store.get(k) | |
| def generateExpiryDate() = LocalDateTime.now().plusDays(daysCacheValidFor) | |
| def valueNotExpired(cachedDated: LocalDateTime): Boolean = | |
| cachedDated.plusDays(daysCacheValidFor).isAfter(LocalDateTime.now()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment