You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Guava:为何需要LoadingCache.refresh?用Cache.invalidate替代可行吗?

Why Use LoadingCache.refresh() When Cache.invalidate() Triggers Automatic Reload?

Great question—this is a common point of confusion with Guava Cache, and the answer boils down to how each method handles existing cache values and request blocking. Let’s break it down clearly:

Core Behavioral Differences

1. Cache.invalidate(key): Hard Removal + Synchronous Blocking

When you call invalidate(key), Guava immediately removes the key from the cache. The next time any thread calls get(key), it will synchronously execute your CacheLoader.load() method to fetch the new value.

  • All concurrent requests for that key will block until the load() method completes.
  • No old value is available during this time—callers wait for fresh data.

2. LoadingCache.refresh(key): Background Refresh + Non-Blocking

refresh(key) takes a gentler approach:

  • It doesn’t remove the old cached value right away. Instead, it kicks off an asynchronous call to CacheLoader.reload() (by default, this just delegates to load(), but you can override it for custom logic like incremental updates).
  • While the refresh is in progress, all incoming requests for the key will still get the existing old value—no blocking, no waiting.
  • Once the refresh finishes, the new value replaces the old one in the cache.

When to Use Which?

Use invalidate() when:

  • The old cached value is completely invalid and cannot be used anymore (e.g., a user’s account was deleted, or a product’s price was updated and showing the old price would cause errors).
  • You’re okay with blocking requests temporarily to ensure everyone gets the fresh, correct data immediately.

Use refresh() when:

  • The old value is still acceptable for a short time (e.g., a dashboard’s hourly stats, or a user’s non-critical profile details).
  • You want to avoid blocking user requests while updating the cache—performance and responsiveness are a priority.
  • You want to implement custom refresh logic (like fetching only changed data instead of reloading the entire record) by overriding reload().

Quick Example

Suppose you have a cache for e-commerce product inventory:

  • If a product is marked as out of stock, use invalidate(productId)—you don’t want anyone seeing old "in stock" data, even if it means a brief delay for the first request.
  • If you’re updating inventory counts throughout the day (which change incrementally), use refresh(productId)—users can see the slightly old count while you refresh the latest numbers in the background, keeping the app fast.

内容的提问来源于stack exchange,提问作者ihadanny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:37:43