views:

148

answers:

1

The python interface to the memcache has an add method:

add(key, value, time=0, min_compress_len=0, namespace=None)

Sets a key's value, if and only if the item is not already in memcache. ...

The return value is True if added, False on error.

So with this you can add an item if it doesn't exist, and see if it previously existed by the return value.

The java memcache api equivalent for this doesn't let you know if there was a previous value or not:

put(key, value, expiration, MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);

MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT: add the value if no value with the key, do nothing if the key exists

Is there a way to know if a previous value existed or not with the java api? I can't just check with the contains method beforehand, because in between the call to contains and the call to put, another JVM instance could modify the memcache.

A: 

The docs say:

The put() method does not return the previous known value for a key. It always returns null.

So if you want to know if it exists before calling put(), I would just call contains() beforehand.

If you're worried about other callers inserting something between your two calls, you may be depending too much on the Memcache being reliable. The Memcache isn't meant to be a reliable place to store important data, just as a cache for more expensive operations (e.g., datastore reads, urlfetches).

Remember that the Memcache can be emptied at any time, for any reason, and your app needs to account for that fact.

Jason Hall