Google Guava Cache - Change the eviction timeout values during run time

浪尽此生 提交于 2019-12-22 13:56:10

问题


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).


来源:https://stackoverflow.com/questions/26843814/google-guava-cache-change-the-eviction-timeout-values-during-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!