如何发布番石榴缓存对象

问题描述 投票:0回答:1

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

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

我的问题是:

  1. 有人教我how to release the old one?我也没有找到任何有用的方法。我只是调用旧的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);
}
java caching guava
1个回答
0
投票

你不需要做任何特别的事来释放旧的;它会像任何其他对象一样被垃圾收集。您可能应该将缓存标记为易失性,甚至更好的是AtomicReference,因此多个线程不会同时替换缓存。也就是说,oldCache应该是方法内部的变量,而不是类。

© www.soinside.com 2019 - 2024. All rights reserved.