5

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?

4
  • You should have a look at the source code :) Commented Nov 5, 2012 at 15:11
  • @PaoloMoretti thanks for the link..what exactly am I looking for.. Commented Nov 5, 2012 at 15:27
  • This question (or one similar) has already been asked on stackoverflow before, I would like to direct you too - stackoverflow.com/questions/2678339/… - serverfault.com/questions/291681/add-vs-set-in-memcached Commented Nov 5, 2012 at 16:02
  • Thanks. My main question is the second part of the question though. It doesn't make sense that using add() still shows a RPC call for set(). That's what I'm mostly confused about.. Commented Nov 5, 2012 at 16:09

1 Answer 1

5

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?

Sign up to request clarification or add additional context in comments.

1 Comment

To be clear, if you just changed set() to add() there's still the possibility of a key collision, it's just that with add() you'll know about it via its return value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.