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