Skip to content

Instantly share code, notes, and snippets.

@ianclegg
Last active January 12, 2017 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianclegg/dc1254a77f815df64ffe2636696df4f2 to your computer and use it in GitHub Desktop.
Save ianclegg/dc1254a77f815df64ffe2636696df4f2 to your computer and use it in GitHub Desktop.
// none of the remaining methods are actually required by the cache directive - but they must be implemented to
// satisfy the spray Cache trait. The equivalent methods offered by ConcurrentLinkedHashMap appeared to be async, but
// with Caffeine we need to use the synchronous view.
def remove(key: Any) = {
Option(store.synchronous().asMap().remove(key)).map(value => Future.successful(value))
}
def clear(): Unit = store.synchronous().invalidateAll()
def keys: Set[Any] = store.synchronous().asMap().keySet().asScala.toSet
def ascendingKeys(limit: Option[Int] = None) = ???
def size = store.synchronous().asMap().size()def remove(key: Any) = {
Option(store.synchronous().asMap().remove(key)).map(value => Future.successful(value))
}
@ben-manes
Copy link

Option(store.synchronous().asMap().remove(key)).map(value => Future.successful(value))

This does look unfortunate. Since AsyncLoadingCache is for conveniency, it may be a bad match and you might prefer to use Cache[K, Future[V]]. Then it will behave exactly like CLHM, but be unaware of the asynchronous nature of the value. That then requires your code to be intelligent, e.g. clean-up failed futures. Various features may not behave ideally, such as expiration starting at the insertion time of the Future rather than when it has materialized. None of these are too critical and Spray's Cache was okay with that, so a direct port may prefer that rather than fake an async call by blocking.

Though I don't know why removal should care about the old value. Most likely you can scan over usages and get away with an invalidate instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment