Concurrent updates


#1

Hi!

I have a stateless EJB for saving documents to couchbase. For each save this EJB makes an update to a field of another document. But if the API receives many concurrent requests the document wont have the correct values at the end of requests. Because all EJBs will execute at the same time the first line of code below and they get the same document to update, instead of wait one another to finish its job and get the correct document to update.

An example of code:

  1. Document docToUpdate = bucket.get(docKey); --> document to be updated in every save
  2. bucket.insert(docToSave);
  3. // some code to update fields of docToUpdate (for example counters, strings, etc)
  4. bucket.update(docToUpdate);

What is the best practice to avoid this, using couchbase?


#2

@ppliatsik I’m pretty sure what you want is compare and swap (cas). On every get, the Document has the cas value set automatically. When you then call bucket.replace() with the new document, the server will only allow it to pass when the cas on the server side is the same you automatically pass in. If not, you’ll get a CASMismatchException and then you can implement a “do/while” loop, rinse and repeat.


#3

@daschl Thanks for the reply!