Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from Guava Cache

Tags:

I am using 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?

like image 462
rayman Avatar asked Oct 06 '14 07:10

rayman


People also ask

Is Guava cache in-memory?

The Guava project is a collection of several of Google's core libraries for string processing, caching, etc. Guava Cache is an in-memory cache used in applications.

Is Guava cache thread-safe?

Cache entries are manually added using get(Object, Callable) or put(Object, Object) , and are stored in the cache until either evicted or manually invalidated. Implementations of this interface are expected to be thread-safe, and can be safely accessed by multiple concurrent threads.

How do I use Guava cache in Google?

Interface Methods Provided to satisfy the Function interface; use get(K) or getUnchecked(K) instead. Returns a view of the entries stored in this cache as a thread-safe map. Returns the value associated with key in this cache, first loading that value if necessary.

What is a Guava cache?

The Guava Cache is an incremental cache, in the sense that when you request an object from the cache, it checks to see if it already has the corresponding value for the supplied key. If it does, it simply returns it (assuming it hasn't expired).


2 Answers

The proper way of doing it would be to use the invalidate method:

mycache.invalidate("somekey"); 

As specified in the API documentation:

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

like image 173
Robby Cornelissen Avatar answered Sep 18 '22 08:09

Robby Cornelissen


You should be using invalidate(key) method to remove individual elements.For bulk removal you can use invalidateAll(keys) method.

In your case you can use

mycache.invalidate("somekey");  

Hope this solves your problem.

like image 42
Atul Sharma Avatar answered Sep 18 '22 08:09

Atul Sharma