Search code examples
garbage-collectionguava

will Guava Map Cache shrink when keys are removed


private Cache<Object, String> cache = CacheBuilder.newBuilder()
        .concurrencyLevel(4)
        .expireAfterAccess(24, TimeUnit.HOURS)
        .initialCapacity(1024)
        .maximumSize(1_00_000)
        .build();
private ConcurrentMap<Object, String> cacheMap = cache.asMap();

this is my code, it's simple and it's just creating a Guava map cache. question is, if I remove() keys from this map, will GC be able to claim memory back from this map? without using weakReference(I am not storing nest objects like Set or Map etc...)?


Solution

  • Yes

    From Guava's Cache.asMap javadoc (emphasis mine):

    Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to the map directly affect the cache.

    And from Guava's Cache Explained wiki page:

    At any time, you may explicitly invalidate cache entries rather than waiting for entries to be evicted.

    You might want to check the whole wiki page instead of the section I highlighted.