java Guava 如何使 CacheBuilder 中的条目过期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10144194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does Guava expire entries in its CacheBuilder?
提问by Cedric Martin
I want to use a CacheBuilder, as recommended here:
我想使用 CacheBuilder,这里推荐:
Java time-based map/cache with expiring keys
However I don't understand whenGuava knows to expire entries.
但是我不明白Guava 什么时候知道条目过期。
How does Guava do it and what performance cost does it incurr?
Guava 是如何做到的,它会带来什么样的性能成本?
回答by Louis Wasserman
Guava team member here.
番石榴团队成员在这里。
The Guava Cache
implementation expires entries in the course of normal maintenance operations, which occur on a per-segment basis during cache write operations and occasionally during cache read operations. Entries usually aren't expired at exactlytheir expiration time, just because Cache
makes the deliberate decision not to create its own maintenance thread, but rather to let the user decide whether continuous maintenance is required.
GuavaCache
实现在正常维护操作过程中使条目过期,这些操作在缓存写入操作期间基于每个段发生,偶尔在缓存读取操作期间发生。条目通常不会在它们的到期时间完全到期,只是因为Cache
故意决定不创建自己的维护线程,而是让用户决定是否需要持续维护。
I'm going to focus on expireAfterAccess
, but the procedure for expireAfterWrite
is almost identical. In terms of the mechanics, when you specify expireAfterAccess
in the CacheBuilder
, then each segment of the cache maintains a linked list access queue for entries in order from least-recent-access to most-recent-access. The cache entries are actually themselves nodes in the linked list, so when an entry is accessed, it removes itself from its old position in the access queue, and moves itself to the end of the queue.
我将专注于expireAfterAccess
,但 的过程expireAfterWrite
几乎相同。在机制方面,当您expireAfterAccess
在 中指定时CacheBuilder
,缓存的每个段都会为条目维护一个链表访问队列,按从最近访问到最近访问的顺序。缓存条目实际上是链表中的节点,因此当一个条目被访问时,它会将自己从访问队列中的旧位置移除,并将自己移动到队列的末尾。
When cache maintenance is performed, all the cache has to do is to expire every entry at the front of the queue until it finds an unexpired entry. This is straightforward and requires relatively little overhead, and it occurs in the course of normal cache maintenance. (Additionally, the cache deliberately limits the amount of work done in a single cleanup, minimizing the expense to any single cache operation.) Typically, the cost of cache maintenance is dominated by the expense of computing the actual entries in the cache.
执行缓存维护时,缓存所要做的就是使队列前面的每个条目过期,直到找到未过期的条目。这很简单,需要的开销相对较小,并且发生在正常的缓存维护过程中。(此外,缓存特意限制了单次清理中完成的工作量,从而最大限度地减少了任何单个缓存操作的费用。)通常,缓存维护的成本主要取决于计算缓存中实际条目的费用。