Guava缓存在异步重新加载线程已在进行时的请求行为

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

Guava cache behavior for requests when an async reload thread is already in progress

问题

从石榴文档此处中可以看到,当收到一个缓存键的请求,且刷新时间已过期,它会启动一个异步线程来刷新键(如果是这样设置的),并返回现有值。但我从文档中没有找到的信息是,如果第一个请求之后立即收到另一个请求,而之前用于刷新的异步线程仍在运行,会发生什么?它会 -

  1. 返回旧数据,并启动另一个用于刷新的异步线程,或者
  2. 它会察觉到另一个刷新线程正在运行,只是返回旧数据,而不会启动新线程。

如果是第一种行为,我会担心如果请求速率非常高,它可能会在后台使用大量资源。

英文:

From the guava documentation here , when a request is received for a cache key for which refresh time has expired, it starts an asynchronous thread to refresh the key if it is setup that way and returns the existing value. What I did not get from the documentation is what happens when another request is received immediately after the first one and the previous async thread for refresh is still running? Will it -

  1. Return the old data AND start another async thread for refresh OR
  2. It sees another refresh thread is running and it just returns the old data without spawning a new thread.

If the behavior is first one, I would be concerned if the request rate is very high, it might end up utilizing significant resources in the background.

答案1

得分: 2

注意,关于refreshAfterWrite的JavaDoc说明如下:

> 刷新操作的语义在LoadingCache.refresh(K)中进行了说明。

这澄清了其行为,如下:

> 如果另一个线程当前正在为{@code key}加载值,则不执行任何操作。如果与此缓存关联的缓存加载器异步执行刷新操作,则该方法可能会在刷新完成之前返回。

该缓存足够智能,能够执行(2),你可以通过编写一个简单的单元测试来轻松验证。

英文:

Note that the JavaDoc for refreshAfterWrite states,
> The semantics of refreshes are specified in LoadingCache.refresh(K)

This clarifies the behavior as,

> Returns without doing anything if another thread is currently loading the value for {@code key}. If the cache loader associated with this cache performs refresh asynchronously then this method may return before refresh completes.

The cache is smart enough to do (2) and you could easily verify that by writing a simple unit test.

huangapple
  • 本文由 发表于 2020年8月31日 06:44:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63662813.html
匿名

发表评论

匿名网友

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

确定