Book Image

Couchbase Essentials

Book Image

Couchbase Essentials

Overview of this book

Table of Contents (15 chapters)
Couchbase Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Concurrency and locking


While the Couchbase SDKs have been written to be thread-safe, your Couchbase applications still must consider concurrency. Whether two users or two threads are attempting to modify the same key, locking is a necessity in order to limit stale data writes. Couchbase Server supports both pessimistic and optimistic locking.

The CRUD operations we've seen so far do not make use of any locking. To see why this is a problem, consider the following C# code:

public class Story 
{
public String Title { get; set; }
  public String Body { get; set; }
  public List<String> Comments { get; set; }
}

var story = bucket.Get<Story>("story_slug").Value;
story.Comments.add("Nice Article!");
bucket.Replace<Story>("story_slug", story);

Now suppose that in the preceding code, in the moments between the get and set calls, the following code ran on another thread (that is, another web request):

var story = bucket.get<Story>("story_slug");
story.Comments.add("Great writing...