8

I tried guava cache recently and was surprised by eviction policy. Although the cache is clearly stated as an lru in docs, but it isn't defacto. For me evictions looks random as my test shows. (the test is to add 100 etnries, get 100 entries, pot different 100 entries, check eviction order) I'd not like to detect some unexpected evictions in runtime. Could you please provide some background behind eviction policy for a size limited Cache. How can i force guava cache to evict like LHM does?

4

1 回答 1

20

Guava 缓存被分割成不同的哈希表,concurrencyLevel以允许多个并发读取和写入。默认concurrencyLevel值为 4。基本上,如果您maximumSize设置为100,那么实际上只会导致四个段中的每一个段获得maximumSize25。这就是maximumSize文档说明的原因:

请注意,缓存可能会在超出此限制之前驱逐条目。随着缓存大小接近最大值,缓存会驱逐不太可能再次使用的条目。

因此,如果偶然有 30 个条目进入一个特定的细分市场,那么其中 5 个条目将被驱逐。

为 a 获得全局最近最少访问的驱逐的唯一方法Cache是通过设置完全关闭并发concurrencyLevel(1)。即使这样,文档也没有对元素的逐出顺序做出任何保证,您也不应该依赖它。

于 2012-04-19T20:33:08.833 回答