I want to get & remove an item from Cache
final Cache<String, PendingRequest> pendingRequest = CacheBuilder.newBuilder().build();
// get first
pendingCall = pendingRequest.getIfPresent(key);
pendingRequest.invalidate(key); // then remove.
I also found another way
pendingCall = pendingRequest.asMap().remove(key);
Does asMap
method clone all the items? Is it a heavy call? Which manner is better if considering performance.
There's no real difference between those calls because Cache#asMap()
is defined as:
Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to the map directly affect the cache.
Calling asMap()
may be slightly less performant (because it's possible a view has to be created) but the time is constant (and negligible) and is an implementation detail (see internal Guava LocalCache
and LocalManualCache
classes for more details).
What's more important, Cache#invalidate(K)
is more idiomatic and I'd recommend using it instead of map view methods (edit after @BenManes' comment below) if you don't need returned value associated with the key, otherwise use map view.