Locking Items Using Cache Item Versioning (Optimistic locking)
There are two types of locking available with NCache. For Pessimistic locking, kindly review Pessimistic Locking section.
In optimistic locking, NCache uses cache item versioning.
CacheItemVersion
is a property associated with every cache item. It is basically a numeric value that is used to represent the version of the cached item which changes with every update to an item. This property allows you to track whether any change occurred in an item or not. When you fetch an item from cache, you also fetch its current version in the cache.You can specify the cache item version in data update call. This update call succeeds only if the current version of the cache item is the same as passed by the client, otherwise it fails. This is used when you want to update a cache item which you have previously read from cache. If someone else has updated the cache item, the update should fail. In this way each client will update only the latest copy of the data and hence maintain data integrity throughout the cache.
CacheItemVersion adds an additional dimension to the development of application using NCache. Optimistic concurrency can be achieved in applications by NCache Item Versioning.
When any item is added in cache, cache item version is returned to the cache client. This value denotes the number of updates performed on a particular data. With every update, item version value is incremented.
To utilize the APIs, include the following namespace in your application:
Alachisoft.NCache.Web.Caching.
Saving Item Version for the First Time
An Add
operation returns CacheItemVersion
. If an item is added for the first
time, a GUID value containing the timestamp of its creation is returned. This
version will be updated accordingly in future operations on this key.
In the following example, you will add a custom data in cache with key
Product:1001
and save its item version. Kindly ensure that the object is
either serialized or registered with NCache Compact serialization framework.
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
string key = "Product:" + product.ProductID;
try
{
CacheItemVersion itemVersion = cache.Add(key, product);
//Save this item Version for future utilization
}
catch (OperationFailedException ex)
{
// handle exception
}
Updating Item with Specific Version
Item versioning can be used to ensure consistency of data in an environment where the cache is being accessed by multiple applications. The item version can be used to ensure that the data being updated is the same as in the cache and has not been updated prior to the update operation by any other cache client.
In the following example, an update is performed on a previously cached item. If the specified version is equal in the cache item, then it will be updated else an exception will be thrown by NCache.
//precondition: itemVersion is saved when item was added in cache
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
product.Category = 5; // updated category
CacheItem cacheItem = new CacheItem(product);
string key = "Product:" + product.ProductID;
//saved itemVersion from add item call
cacheItem.Version = itemVersion;
try
{
CacheItemVersion newVersion = cache.Insert(key, cacheItem);
//save new version for future usage
//verify the updated version and value in cache
}
catch (OperationFailedException ex)
{
// handle exception
}
Retrieving Cached Item with Specific Version
You can retrieve a cached item by specifying the item version. In case of a mismatch of version, “null” value is returned.
In the following example you need to specify the key and its previously saved item version to fetch the cached object.
//precondition: itemVersion is saved when item was added or inserted in cache
try
{
string key = "Product:1001";
//saved itemVersion from add or insert item call
CacheItem result = cache.GetCacheItem(key, ref itemVersion);
if (result.Value != null)
{
if (result.Value is Product)
{
Product product = (Product)result.Value;
}
}
}
catch (OperationFailedException ex)
{
// handle exception
}
Retrieve Item if a Newer Version Exists in Cache
GetIfNewer
method can be used to fetch the existing item if a newer version is
available in cache. By specifying the current version as an argument of the
method call, the cache returns appropriate result.
If the version specified is less than the one in cache, only then the method returns a new Item else null would be returned.
//precondition: itemVersion is saved when item was added or inserted in cache
string key = "Product:1001";
try
{
//saved itemVersion from add or insert item call
object result = cache.GetIfNewer(key, ref itemVersion);
if (result != null)
{
if (result is Product)
{
Product product = (Product)result;
}
}
}
catch (OperationFailedException ex)
{
// handle exception
}
Removing an Item with Specified Item Version
The Remove
method is a basic method which removes the key from cache and returns
the removed object to the cache. If a custom object is added to the cache, the
remove method will return Object.
If the item version is different from the one in the cache or if the key does not exist, an OperationFailedException will be thrown by NCache.
//precondition: itemVersion is saved when item was added or inserted in cache
string key = "Product:1001";
try
{
//saved itemVersion from add or insert item call
object result = cache.Remove(key, itemVersion);
if (result != null)
{
if (result is Product)
{
Product product = (Product)result;
}
}
}
catch (OperationFailedException ex)
{
// handle exception
}
Delete an Item with Item Version
A Delete
method is a basic method which deletes the key from cache. If the item
version is different from the one in the cache or if the key does not exist, an
Exception will be thrown by NCache.
//precondition: itemVersion is saved when item was added or inserted in cache
string key = "Product:1001";
try
{
//saved itemVersion from add or insert item call
cache.Delete(key, itemVersion);
}
catch (OperationFailedException ex)
{
// handle exception
}