Andrew_3w
Andrew_3w

Reputation: 5

Java Guava Cache: how to get entires after expiration

I am trying to use Java Guava Cache and I set my cache to expire some time after value has been written:

Cache<String,String> myCache=CacheBuilder.newBuilder().expireAfterWrite(40, TimeUnit.SECONDS).build();

In my code I need to check if subset of particular keys is present in myCache`` and if so I build another HashMap with those keys:

if (myCache.asMap().keySet().equals(mySet()) {
    Map<String,String> myMap=myCache.asMap().entrySet().stream().filter(...).collect(Collectors.toMap(...));
}

My question is about edge case. Let's say once we checked that particular subset of keys presents in myCache(myCache.asMap().keySet().equals(mySet()), cache entries with those keys expired and not available anymore. So we checked that keys were in myCache but we cannot get any values because they just expired. How can we handle such use-case and "lock" our cache once we checked for particular keys?

Upvotes: 0

Views: 855

Answers (1)

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28045

Just useCache#getAllPresent(Iterable) which "Returns a map of the values associated with keys in this cache. The returned map will only contain entries which are already present in the cache."

ImmutableMap<String, String> presentEntries = myCache.getAllPresent(mySet());

Upvotes: 0

Related Questions