Snowman
Snowman

Reputation: 32061

Using memcache.add() instead of set()

Usually I do:

if not memcache.get('mykey'):
   memcache.set('mykey', item)

However, today I saw memcache.add(), which appears to add an item only if it doesn't already exist. So is this equivalent to the code I have above? Can I just replace the code above with memcache.add()?

Also, and more importantly, I'm using AppStats, and under RPC Call Traces, I get to see if my request calls memcache.set() or get() or datastore.put() or get(). When using the 2 lines of code above, I don't see anything for memcache.set(), which is expected. However, using only memcache.add() (without checking if the item already exists) always calls memcache.set(), even though memcache.add() returned false (meaning a new item was not inserted). Why is this the case?

Upvotes: 5

Views: 5130

Answers (1)

Nick Johnson
Nick Johnson

Reputation: 101139

Your current code has a race condition: between checking for the presence of a value in memcache and inserting it, another process could have inserted a value, which you'll now overwrite. Using memcache.add does not suffer from this race condition.

I'm not sure what you mean by your second question; calling memcache.add should result only in an add call, never a set call. Can you include the code you're running in that case?

Upvotes: 5

Related Questions