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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:30:02  来源:igfitidea点击:

Remove elements from Guava Cache

javacachinghashmapguava

提问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 invalidatemethod:

正确的做法是使用以下invalidate方法:

mycache.invalidate("somekey");

As specified in the API documentation:

API 文档中所述

void invalidate(Object key)
Discards any cached value for key key.

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.

希望这能解决您的问题。