Search code examples
javamemcachedspymemcached

Check whether a key exists in memcached ( spymemchaced - Java memcached client)


I wanna perform a code which has pseudo-code like this:

MemcachedClient c = new MemcachedClient(....)
if c.get("key") exists 
  print(c.get("key"))
else 
  c.add("key",expTime, value)

The problem is: how can I check whether c.get("key") exists?


Solution

  • The get(String key) method returns null if there is no key associated with the key.

    Therefore, you can get the value, and check if it is null to know if it "exists":

    Object myObject = c.get("key");
    if(c == null) { // the object does not exist
        // add the value
    } else {
        System.out.println(myObject);
    }