Guava LoadingCache:为什么要同时使用 refreshAfterWrite 和 expireAfterWrite

Guava LoadingCache: Why use refreshAfterWrite and expireAfterWrite together

我阅读了这篇解释 Guava 缓存的文档:CachesExplained。我确实了解 refreshAfterWrite 和 expireAfterWrite 在做什么。不过文档在解释refreshAfterWrite的时候也提到了这个:

"因此,例如,您可以在同一个缓存上同时指定 refreshAfterWrite 和 expireAfterWrite,这样条目的过期计时器就不会在条目符合刷新条件时盲目地重置,因此,如果一个条目在符合刷新条件后未被查询,则允许它过期。"

这是让我感到困惑的部分。我的理解是,如果想让某个key自动刷新,只需要指定refreshAfterWrite即可。为什么我们甚至想在使用 refreshAfterWrite 时使用 expireAfterWrite?

在某些情况下,您希望缓存的条目相关,因此您设置了刷新持续时间(这可能更容易执行(和异步),而不是在逐出后完全获取,因此不同) ,但与此同时,如果您的缓存是有界的,您将想要逐出条目,这就是 expireAfterWrite 的用途。通过同时设置它们,您将确保条目在特定时间后被逐出,即使它已被刷新。

另请注意,两者的操作方式不同:

Refreshing is not quite the same as eviction. As specified in LoadingCache.refresh(K), refreshing a key loads a new value for the key, possibly asynchronously. The old value (if any) is still returned while the key is being refreshed, in contrast to eviction, which forces retrievals to wait until the value is loaded anew.