Using a combination of Optimistic and Pessimistic Locking?

Continuing the discussion from Optimistic / Pessimistic locking in 2.1.x driver:

Just want to make sure I understand this correctly. Let’s suppose that there are two code paths intending to modify the same document and one does a getAndLock and the other does a get. A few questions now…

  • If the latter does an upsert/replace before the former then is the lock effectively nullified?
  • What happens when the former does an upsert/replace? I am assuming CAS will come into play ensuring data integrity.

In other words, for the locking mechanism to be used effectively all access to the document should use getAndLock.

Currently in one code path of our application, documents are fetched with lock, modified and written back one at a time (because contextually there is only one document that we have to deal with in this code path). In a different code path many documents need to be read, modified and written back. We are doing a bulk read, modify and bulk write for performance reasons. So, getAndLock might not be correct in this scenario.

Are there any recommendations with regards to ensuring data integrity and performance? Is using a get and handling CAS related exception the right way to go?