Why does Cache.asMap () not match Cache.size ()?

In the Guava Library, I am confused about why Cache.asMap() not consistent with Cache.size() unless Cache.cleanUp() 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 

So my question is: is it a bug that Cache.asMap() does not match Cache.size() ? Although I noticed that javadoc Cache.size() :

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

I just think this is due to the parallel environment. And what exactly does Cache.cleanUp() do?

+7
source share
2 answers

The Guava cache is designed to cushion the lock, and the cleanUp method causes the cache to arrive in a consistent state. The Map.size() method is approximate, but can count records pending deletion due to an expiration or eviction link. The visibility of approximations in the Guava cache is rarely of great interest to an application, which usually considers the cache as a temporary data store. Various expectations of the cache from the Map led to the asMap method to allow the cache to be considered as a map, but developers do not like to perceive it in this way.

Details of the cache implementation were described at the StrangleLoop 2011 slides conference. The ConcurrentLinkedHashMap project document from which the GuoWa cache was obtained may also be of interest, but it describes a slightly different approach.

+13
source

Ben gave a good high-level answer. Low level answer:

In submissions

asMap() is the luxury of passing every item in the cache and, therefore, can skip invalid entries that are waiting to be cleared. On the other hand, it is expected that size() will be a quick operation, and it would be foolish to traverse the entire cache to get a more accurate estimate of the size.

CacheBuilder javadocs will talk in more detail about the cleanup that needs to happen in various situations (for example, expireAfterWrite , in your case).

+9
source

All Articles