在我的应用程序中,我通过CacheBuilder.newBuilder()方法构建了一个Guava Cache对象,现在我需要为它动态调整一些初始化参数。
由于我没有找到任何用于番石榴缓存的重建方法,我必须重建一个新的方法。
我的问题是:
how to release the old one
?我也没有找到任何有用的方法。我只是调用旧的cache.invalidateAll()来使所有键无效。 Is there any risk for OOM
?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应该是方法内部的变量,而不是类。