caching - Guava 缓存 'expireAfterWrite' 似乎并不总是有效

标签 caching guava

private Cache<Long, Response> responseCache = CacheBuilder.newBuilder()
            .maximumSize(10000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build();

我期望在 10 分钟内未发送到客户端的响应对象过期并自动从缓存中删除,但我注意到即使在 10、15、20 分钟后响应对象也并不总是过期。当缓存被大量填充时,它们确实会过期,但是当系统空闲时,比如最后 500 个响应对象,它会停止删除这些对象。
有人可以帮助理解这种行为吗?谢谢

最佳答案

这在文档中指定:

If expireAfterWrite or expireAfterAccess is requested entries may be evicted on each cache modification, on occasional cache accesses, or on calls to Cache.cleanUp(). Expired entries may be counted by Cache.size(), but will never be visible to read or write operations.



维基上有更多详细信息:

Caches built with CacheBuilder do not perform cleanup and evict values "automatically," or instantly after a value expires, or anything of the sort. Instead, it performs small amounts of maintenance during write operations, or during occasional read operations if writes are rare.

The reason for this is as follows: if we wanted to perform Cache maintenance continuously, we would need to create a thread, and its operations would be competing with user operations for shared locks. Additionally, some environments restrict the creation of threads, which would make CacheBuilder unusable in that environment.

Instead, we put the choice in your hands. If your cache is high-throughput, then you don't have to worry about performing cache maintenance to clean up expired entries and the like. If your cache does writes only rarely and you don't want cleanup to block cache reads, you may wish to create your own maintenance thread that calls Cache.cleanUp() at regular intervals.

If you want to schedule regular cache maintenance for a cache which only rarely has writes, just schedule the maintenance using ScheduledExecutorService.

关于caching - Guava 缓存 'expireAfterWrite' 似乎并不总是有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026878/

相关文章:

java - 如何使用反射和 Guava TypeToken 实例化参数化类的 Class 对象

php - Symfony2 : Same codebase with multiple environments leads to tons of cache files

node.js - 如何始终禁用 Chrome 网络缓存

caching - 维护包含 ESI 的请求的 session

hsqldb - 使用hsqldb时缓存的表不是缓存而是在内存中

java - 使用 MultiMap 的优先级队列 - Java

java - Guava Striped 的正确条纹数是多少?

java - Guava 是否提供对定义字符范围的支持?

java - 不可变但可刷新的集合?

caching - 使用 Fiddler 确认 HTTP 缓存