如何释放番石榴缓存对象

How to release a guava cache object

在我的应用中,我通过CacheBuilder.newBuilder()方法构建了一个Guava Cache对象,现在我需要为其动态调整一些初始化参数。

因为我没有找到任何重建番石榴缓存的方法,我必须重建一个新的。

我的问题是:

  1. 有人教我吗how to release the old one?我没有找到任何有用的方法 either.I 只需为旧方法调用 cache.invalidateAll() 即可使所有密钥无效。 Is there any risk for OOM ?

  2. 由于缓存可能在多线程中使用,是否需要将缓存声明为volatile

我的代码如下:

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);
}

您不需要做任何特别的事情来发布旧版本;它会像任何其他对象一样被垃圾收集。您可能应该将缓存标记为易失性,或者更好的标记为 AtomicReference,这样多个线程就不会同时替换缓存。也就是说,oldCache 应该是方法内部的一个变量,而不是 class.