【发布时间】:2015-06-07 21:51:11
【问题描述】:
假设我有一个服务器,它根据客户端请求调用一个耗时的函数slow: Int => String。如果slow 未在timeout 内返回,则服务器向客户端返回错误。
def trySlow(timeout: Duration)(id: Int): Try[String] = {
val fut = Future(slow(id))
try {
Await.ready(fut, timeout).value match {
case Some(r) => r
case None => Failure(new TimeoutException()) // should not happen
}
} catch {
case e: TimeoutException => Failure(e)
}
}
现在我想缓存未来,以便使用相同id 调用trySlow 的多个线程将等待相同的未来。
我将使用一个可变并发TrieMap来实现一个单例缓存。
case class CacheEntry (
future: Future[String],
start: Long = System.currentTimeMillis() // need it to clean the cache
)
type Cache = TrieMap[Int, CacheEntry]
def trySlow(timeout: Duration, cache: Cache)(id: Int): Try[String] = {
val fut = cache.getOrElseUpdate(id, CacheEntry(Future(slow(id))))
... // as in above
}
这有意义吗? immutable non-singleton 缓存如何做到这一点?
【问题讨论】:
标签: scala caching concurrency future