Search code examples
javacachingguava

Manage entries in Google Guava Cache


I need to develop a Spring Boot micro service with embedded database (Derby) with cache (Guava cache).

The size of the entries is different in each customer.

  • If I'll not set maximumSize, what will happened? the size will grow constantly? it will effected the size? memory?
  • If I'll scheduled a job that preform cleanUp (for each interval), when the entries will remove from the cache? and how it will effected if I've only refreshAfterWrite?
  • Lets say I set refreshAfterWrite without any call to cleanUp, the the expired entries will removed from the cache? (i.e., I'll call to cache.size() and see that it has been decreased).

Thanks


Solution

  • That's a lot of questions. They're all explained on the CachesExplained wiki page of Guava.

    If I'll not set maximumSize, what will happened? the size will grow constantly?

    What will happen is that entries will be freed when other conditions are met, or when there is no memory available anymore. So yes, the size will grow as long as those conditions aren't met. (Section "Size-based Eviction")

    it will effected the size? memory?

    maximumSize(long) specifies a specific object size. By default it's the number of elements that are present in the cache. But if you use weigher(Weigher), you can say that a specific element is worth more or less, so making it closer to the actual memory usage. But you have to write your own Weigher, then. (Section "Size-based Eviction")

    If I'll scheduled a job that preform cleanUp (for each interval), when the entries will remove from the cache?

    The entries will be purged when you call the cleanUp() method. (Section "When Does Cleanup Happen?")

    and how it will effected if I've only refreshAfterWrite?

    If you call cleanUp() with a refreshAfterWrite cache, the entry you wish to access will have to be loaded again, no matter if the refreshAfterWrite was triggered or not.

    Lets say I set refreshAfterWrite without any call to cleanUp, the the expired entries will removed from the cache?

    No, refreshAfterWrite is not the same as expireAfterWrite. The entry will be eligible for refresh, but will not be removed. If you used expireAfterWrite, then the entry will expire and be removed.

    (i.e., I'll call to cache.size() and see that it has been decreased).

    That's not how it works. Cache is not a guaranteed worker. It's not like a collection. It's possible that some entries aren't taken into account when calculating the size, or that some entries are still counted as part of the size, but not yet effectively removed. This is explicitly written in the Javadoc for the size() method:

    size

    long size()
    

    Returns the approximate number of entries in this cache.

    Basically, you should really read the whole documentation of Guava's CachesExplained wiki page. All the actual info is there, in a very descriptive way.