java 从番石榴缓存中删除元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26211684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove elements from Guava Cache
提问by rayman
I am using import com.google.common.cache.Cache
我在用 import com.google.common.cache.Cache
I have initiated the cache this way:
我以这种方式启动了缓存:
private Cache<String,String> mycache =CacheBuilder.newBuilder()
.concurrencyLevel(4).expireAfterAccess(30, TimeUnit.MINUTES).build();
I am willing to remove entries manually in some scenarios before waiting for the expiration.
在某些情况下,我愿意在等待到期之前手动删除条目。
The only way I found to do this was this:
我发现这样做的唯一方法是:
mycache.asMap().remove("somekey");
I am asking if that is the proper way of doing this? Am I going to have any problems with that?
我在问这是否是这样做的正确方法?我会遇到任何问题吗?
回答by Robby Cornelissen
The proper way of doing it would be to use the invalidate
method:
正确的做法是使用以下invalidate
方法:
mycache.invalidate("somekey");
As specified in the API documentation:
void invalidate(Object key)
Discards any cached value for keykey
.
void invalidate(Object key)
丢弃 key 的任何缓存值key
。
回答by Atul Sharma
You should be using invalidate(key)
method to remove individual elements.For bulk removal you can use invalidateAll(keys)
method.
您应该使用invalidate(key)
方法来删除单个元素。对于批量删除,您可以使用invalidateAll(keys)
方法。
In your case you can use
在您的情况下,您可以使用
mycache.invalidate("somekey");
Hope this solves your problem.
希望这能解决您的问题。