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?
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.
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.
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.
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).
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 keykey
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With