Optimistic / Pessimistic locking in 2.1.x driver



Could someone tell me what has replaced com.couchbase.client.CouchbaseClient (a class that does not appear to be available in java-client- 2.1.2.jar or any of the associated JARs pulled in with Maven)? Is the lock effected by Bucket::getAndLock(…) an optimistic lock? If so, how is pessimistic locking done?




Hey Matthew, I’m gonna ask @ingenthr to take a look at this when he gets online later today. Much of our Java team is Europe based and it’s a public holiday in much of Europe today.



In the 2.x client, we intentionally changed the packaging structure for two reasons. One is that it’s a new major version with new API. Second is that we wanted people to be able to run the 1.x and the 2.x in the same app concurrently to facilitate slower migrations.

You can see the 2.x API in the API reference, as linked off of the documentation.

With regard to getAndLock(), it’s actually best characterized as a cooperative pessimistic lock with a timeout. What that means is as long as all code paths are using the same getAndLock() access path, only one will succeed with the lock if many actors are going after it once, and the others will then learn that it’s locked. It’s that actor’s responsibility to unlock the document with either an unlock or a CAS operation. If it doesn’t do so within a timeout period, then the lock will be released.

The CAS based optimistic locking is, of course, still there and I personally think it’s generally the preferred approach if you can refactor the problem in that way.

I usually see the getAndLock() type approach to be best used if your application is grabbing a graph of objects for update and wants reasonable assurances (with no failures) that it has exclusive access. However, it’s up to the app to handle the failure cases.

Using a combination of Optimistic and Pessimistic Locking?

Thanks for the details. I assume that the ‘CAS based optimistic locking’ will be rolled up into a later version of the driver


It is there now and has been since the beginning. It’s covered in the documentation. The Document interface has a CAS property and it must match or be zero for operations with those documents to be accepted.


@couchbaseuser024 exactly what @ingenthr said.

When you “get” a document, the CAS value is automatically populated. When you then use the replace() operation the CAS will be taken into account and if the optimistic locking fails, you’ll see a CASMismatchException/error depending if you are on the async or sync APIs.