3

Is there a way to see if a particular key exist in cacheManager (org.springframework.cache.CacheManager) as i am unable to find a way to do that as there is no containsKey option. I would appreciate if someone could show me a way to check if a key exist in cacheManager. Below are few things i have tried so far -

Cache cache=null;
for (String name : cacheManager.getCacheNames()) {
    cache=cacheManager.getCache(name);
    System.out.println("-------------->"+cache.get("dummyCache").get()); //this will give me null pointer exception as there is no dummyCache 
    }

I would like add if/else check to see if a dummyCachekey exist in cache

Jon Abraham
  • 851
  • 3
  • 14
  • 27
  • so if i understand this right then when i do cache.get("foo") that means "foo" key already exist in cache and is not null but what if i want to check if "foo" exist in cache – Jon Abraham May 19 '20 at 18:00
  • Aweome that answers my question thank you for clarifying – Jon Abraham May 19 '20 at 18:04

1 Answers1

7

You can simply check the value returned by Cache.get for null.

From the relevant documentation (emphasis by me):

Returns the value to which this cache maps the specified key, contained within a Cache.ValueWrapper which may also hold a cached null value. A straight null being returned means that the cache contains no mapping for this key.

So

  • cache.get("foo") == null means: The key "foo" does not exist in the cache
  • cache.get("foo").get() == null means: The key "foo" does exist in the cache, but its value is null
Marvin
  • 13,325
  • 3
  • 51
  • 57