rayman rayman - 3 months ago 32
Java Question

Remove elements from Guava Cache

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?

Answer

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.

Comments