Google Guava Cache - Change the eviction timeout v

2019-05-28 22:15发布

问题:

I am using the following:

LoadingCache<String, Long> inQueueLoadingCache = CacheBuilder.newBuilder()
    .expireAfterWrite(120, TimeUnit.SECONDS)
    .removalListener(inQueueRemovalListener)
    .build(inQueueCacheLoader);

After every 120 seconds, the cache entries are evicted and it works as expected.

My question is: How do I change the timeout value, say from 120 to 60 seconds, for the current cache? What will happen to the cache entries during this change?

回答1:

Short answer: you can't change eviction timeout value, or any property of Cache / LoadingCache created by CacheBuilder.

Anyway, why would you want to change the timeout? (Also bare in mind that Guava Caches are quite simple.) If you really do want to change the timeout, you have two choices:

  • create new Cache with target semantics and copy old cache contents, ex.

    LoadingCache<String, Long> newCache = CacheBuilder.newBuilder()
        .expireAfterWrite(60, TimeUnit.SECONDS)
        .removalListener(inQueueRemovalListener)
        .build(inQueueCacheLoader);
    newCache.putAll(inQueueLoadingCache.asMap());
    

    but you'll loose original access times etc.

  • don't use CacheBuilder at all and implement LoadingCache yourself, for example using AbstractLoadingCache skeletal implementation with your own policy for changing timeouts. It's not easy though, because you have nice LoadingCache's API but you have to implement whole thing by yourself (I tried it once but ended using more advanced cache than Guava's one).