本文介绍了为什么Cache.asMap()与Cache.size()不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Guava图书馆中,我对为什么与,除非被调用。

In the Guava Library, I am confused about why Cache.asMap() is not consistent with Cache.size(), unless Cache.cleanUp() is called.

Cache<Object, Object> cache = CacheBuilder.newBuilder()
           .expireAfterWrite(1, TimeUnit.SECONDS)
           .build();
cache.get(...);
...
//After some seconds, all entries are expired.
//cache.asMap() is EMPTY Map, but cache.size() != 0

所以我的问题:是否是 Cache.asMap() Cache.size()
虽然我注意到 Cache.size()的javadoc是:

So my question: Is it bug that Cache.asMap() is not consistent to Cache.size()? Although I notice the javadoc of Cache.size() is:

  /**
   * Returns the **approximate** number of entries in this cache.
   */



我可以猜测它与一个并发环境有关。
Cache.cleanUp()做什么?

推荐答案

Guava的缓存是围绕锁分期偿还设计的, cleanUp 方法强制缓存达到一致的状态。 Map.size()方法是一种近似,但可能会由于过期或引用逐出而对待删除的条目进行计数。 Guava的缓存中的近似的可见性对于应用程序很少感兴趣,这倾向于将缓存看作暂时数据存储。缓存从Map的不同期望导致 asMap 方法允许缓存被视为一个映射,但是不利于开发者以这种方式感知它。

Guava's cache is designed around lock amortization and the cleanUp method forces the cache to arrive at a consistent state. The Map.size() method is an approximation, but may count entries pending removal due to expiration or reference eviction. The visibility of the approximations in Guava's cache are rarely of much interest to an application, which tends to think of a cache as a transient data store. The different expectations of a cache from a Map led to the asMap method to allow the cache to be viewed as a map, but disfavor developers perceiving it that way.

缓存的实现细节已在StrangleLoop 2011年会议,Guava的缓存源自,也可能是感兴趣的,但描述了一种稍微不同的方法。

The implementation details of the cache was covered in the StrangleLoop 2011 conference slides. The design document of ConcurrentLinkedHashMap, which Guava's cache was derived from, may also be of interest but describes a slightly different approach.

这篇关于为什么Cache.asMap()与Cache.size()不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 08:58