guava的LoadingCache.refresh – 如果我们可以使用Cache.invalidate,为什么需要它呢?

huangapple go评论74阅读模式
英文:

guava LoadingCache.refresh - why do we need it if we can just Cache.invalidate?

问题

使用guava - 为什么我们需要 LoadingCache.refresh
难道我们不能只使用 Cache.invalidate,然后在下一次 get 时值会被刷新吗?

英文:

Using guava - why do we need LoadingCache.refresh?
Can't we just use Cache.invalidate and on our next get the value would be refreshed?

答案1

得分: 1

以下是翻译好的内容:

语义如下:

  • LoadingCache.refresh:现有映射仍然存在,缓存继续返回存储的值,直到新值可用。
  • Cache.invalidate:映射被丢弃。下一次调用 LoadingCache.get() 时将加载新值。

如果你的应用程序使用了 LoadingCache.get(),在这两者之间可能没有“逻辑”差异。如果发生(可能是大量的)并发请求,那么应用程序的行为将会有所不同:

  • 使用 LoadingCache.refresh,应用程序将不断提供请求。加载器的响应时间不会影响应用程序的响应时间。
  • 使用 LoadingCache.get(),请求可能会阻塞,直到加载完成。这可能会变得危险,例如,假设每秒有 1000 个请求,而加载需要 5 秒钟。这意味着有 5000 个请求将被阻塞,并正在等待响应。如果一个应用程序请求依赖于多个缓存和加载器,情况可能会更糟。
  • 然而,使用 LoadingCache.refresh 仍然会提供一个可能过时的值。如果需要一致性,则无法使用它。

主要结论:

如果不同时刷新,加载时间将累加到应用程序的响应时间中,并且会加剧用户体验的恶化。

英文:

The semantics are:

  • LoadingCache.refresh: The existing mapping is still present and the cache continues to return the stored value until the new value is available
  • Cache.invalidate: The mapping discarded. A new value would be loaded upon the next LoadingCache.get()

If your application uses LoadingCache.get() there may be no "logic" difference between both. If (maybe lots) of concurrent requests happen, then the application will behave differently:

  • With LoadingCache.refresh the application will constantly serve requests. The loader response time does not effect the application response time.
  • With LoadingCache.get(), requests might block until the loading is completed. This might get dangerous, for example, lets say there are 1000 requests per second and your loading takes 5 seconds. That would mean that 5000 requests would be blocked and are waiting for the response. If one application request depends on multiple caches and loaders, this might be even worse.
  • However, with LoadingCache.refresh you are still serving an possibly outdated value. You cannot use it if you need consistency

Main take away:

If not refreshed concurrently the load times add to your application response time and worsen the user experience.

huangapple
  • 本文由 发表于 2020年9月29日 17:49:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64117095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定