Search code examples
javacachingguava

How to release a guava cache object


In my application, I build a Guava Cache object by CacheBuilder.newBuilder() method, and now I need to dynamically adjust some initialization parameters for it.

As I don't find any rebuild method for a guava cache, I have to rebuild a new one.

My question is :

  1. Anybody teach me how to release the old one ? I don't find any useful method either.I just call cache.invalidateAll() for the old one to invalidate all the keys. Is there any risk for OOM ?

  2. As the cache maybe used in multi-threads, is it necessary to declare the cache as volatile ?

my codes is as belows:

private volatile LoadingCache<Long, String> cache = null;
private volatile LoadingCache<Long, String> oldCache = null;

public void rebuildCache(int cacheSize, int expireSeconds) {
    logger.info("rebuildCache start: cacheSize: {}, expireSeconds: {}", cacheSize, expireSeconds);
    oldCache = cache;
    cache = CacheBuilder.newBuilder()
        .maximumSize(cacheSize)
        .recordStats()
        .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
        .build(
            new CacheLoader<Long, String>() {
                @Override
                public String load(Long id) {
                    // some codes here
                }
            }
        );
    if (oldCache != null) {
        oldCache.invalidateAll();
    }
    logger.info("rebuildCache end");
}

public String getByCache(Long id) throws ExecutionException {
    return cache.get(id);
}

Solution

  • You don't need to do anything special to release the old one; it'll get garbage collected like any other object. You probably should mark the cache as volatile, or even better, an AtomicReference so multiple threads don't replace the cache at the same time. That said, oldCache should be a variable inside the method, not the class.