Exclusive Locks on Items (Pessimistic Locking)
NCache provides a Pessimistic Locking mechanism that exclusively locks the cached data. This mechanism locks the item using the lock handle due to which, all other users are blocked from performing any write operation on that cache item. A LockHandle
is associated with every locked item in the cache, which is returned by the Locking API.
Note
This feature is also available in NCache Professional.
A locked item can be fetched/updated or unlocked only when its lock handle is provided at the API level. However, you should do this with care to avoid data integrity issues. Pessimistic Locking is a very good approach if the goal to be achieved is data consistency.
Once a lock is acquired using LockHandle
, there are two mechanisms for releasing it. Both of these mechanisms are explained below.
Time-based release of locks: You can also specify lock timeout while Locking a cached item. The lock timeout is the time interval after which the lock will be automatically released if no explicit call is made for releasing the lock during the timeout interval. This will prevent your data from being locked for an infinite amount of time.
Forceful release of locks: Situations can arise in distributed environments when an application that acquired the lock on a cache item terminates abruptly or an application finalizes its processing on locked data. In such a situation you would like to release all locks acquired by such an application. NCache provides an unlock API, which releases the cache item lock forcefully.
Note
It is recommended to use a time-based locking mechanism to ensure that the item is automatically unlocked after a specified duration, minimizing the time resources remain acquired and improving overall system efficiency.
When to Use Pessimistic Locking
Take the example discussed in the former chapter. If the same bank account is accessed by two different users at the same instance for an update operation, a conflict might occur which will lead to data inconsistency.
Pessimistic Locking in this scenario will enable one user to access the account at one time. On operating successfully, the user unlocks the item and the control is set free which means the second user can now access the account and make amends accordingly. Using this approach, the data remains consistent and no conflict occurs.
A LockHandle
is associated with an item to ensure that the particular item remains
inaccessible throughout the cache. NCache provides a method that calls exclusively for Locking, as well as, numerous overloads that manipulate the Locking mechanism.
Prerequisites
- To learn about the standard prerequisites required to work with all NCache client-side features, please refer to the given page on Client-Side API Prerequisites.
- For API details, refer to: ICache, Contains, Count, Insert, Lock, LockHandle, Remove, TimeSpan, Unlock.
Lock an Item Explicitly
You can explicitly lock an item before performing any operation. This method requires a TimeSpan
to lock an item for a specified time. However, if you do not want the acquired lock to expire specify TimeSpan.Zero
. Specifying no TimeSpan
will lock the item for an infinite time.
The Lock
method used in this example associates a LockHandle
with a key. Kindly ensure that the single LockHandle
is associated with a single key. Release the lock before reusing the handle, otherwise, it might lead to inconsistency of behavior. If an item is already locked, then the false value will be returned, but you will get the updated LockHandle
.
Warning
Lock an item for the minimum TimeSpan
to avoid a deadlock or starvation state.
The following example creates a LockHandle
and then locks an item with the key Product:1001
for a time span of 10 seconds which means the item will be unlocked automatically after 10 seconds.
// Precondition: Cache is already connected
// Item is already added in the cache
// Specify the key of the item
string key = $"Product:1001";
// Create a new LockHandle
LockHandle lockHandle = null;
// Specify time span of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Lock the item for a time span of 10 seconds
bool lockAcquired = cache.Lock(key, lockSpan, out lockHandle);
// Verify if the item is locked successfully
if (lockAcquired == true)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Lock an Item during Get Operation
An item can be locked during its retrieval from the cache. This means that the item will be inaccessible to others unless you release it. In case of keys mismatch, a null value is returned.
If an item is not locked and the
acquirelock
is set to true, then you will get the item along with theLockHandle
.If an item is locked and
acquirelock
is set to false and if you pass an incorrect or new emptyLockHandle
, then anull
value is returned, but you will get theLockHandle
which was used to lock the item previously.If an item is locked and
acquirelock
is set to false and correctLockHandle
is passed which was previously used to lock the item, then you will get the value.
Warning
Lock an item for the minimum TimeSpan to avoid deadlock or thread starvation.
In this example, a key and LockHandle
is specified to fetch
the cached object and lock it. You need to set to true if you need to acquire the lock. Here the item is locked with an expiration of 10 seconds which means the item will be unlocked automatically after 10 seconds.
// Specify the key of the item
string key = $"Product:1001";
// Set acquireLock flag as true
bool acquireLock = true;
// Specify time span of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Create a new LockHandle
LockHandle lockHandle = null;
// Lock the item for a time span of 10 seconds
var result = cache.Get<Product>(key, acquireLock, lockSpan, ref lockHandle);
// Verify if the item is locked successfully
if (result != null)
{
// Item has been successfully locked
}
else
{
// Key does not exist
// Item is already locked with a different LockHandle
}
Release Lock with Update Operation
While updating an item, you can release the lock, allowing others to use the
cached data. To successfully release the locked item, you will need to specify the LockHandle
initially used to lock the item.
The
LockHandle
should be the same as the one used initially to lock the item, otherwise, you will get an exception message saying "Item is Locked".If
releaseLock
is set to false you still have to pass the correctLockhandle
to update the item.If an item is not locked, then the
LockHandle
andreleaseLock
are of no use and they are ignored.
The following example locks an item in the cache and then gets the item using the LockHandle
. The item is then updated and then reinserted in the cache using the Insert API.
// Specify the key of the item
string key = $"Product:1001";
// Set acquireLock flag as true
bool acquireLock = true;
// Specify time span of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);
// Initialize the lockHandle
LockHandle lockHandle = null;
CacheItem item = cache.GetCacheItem(key, acquireLock, lockSpan, ref lockHandle);
var product = new Product();
product = item.GetValue<Product>();
// Update the unitsinstock for the product
product.UnitsInStock = 200;
bool releaseLock = true;
// Item is already locked with a LockHandle
// Update the item and release the lock as well since releaseLock is set true
// Make sure that the LockHandle matches with the already added LockHandle
cache.Insert(key, item, null, lockHandle, releaseLock);
Release Lock Explicitly
To release the lock explicitly on a previously locked cached item, you will need to specify the LockHandle
initially used to lock the item. If the LockHandle
is not saved, you can also use another overload of Unlock
which only takes the key to unlock the item.
Note
If an invalid LockHandle
is passed, then no exception will be thrown but the item will remain locked.
The following example gets an item already locked using the LockHandle
and then unlocks it using the Unlock
API using the Lockhandle
saved before.
// Specify the key of the item
string key = $"Product:1001";
// Set acquireLock flag as true
bool acquireLock = true;
// Specify time span of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Create a new LockHandle
LockHandle lockHandle = null;
Product result = cache.Get<Product>(key, acquireLock, lockSpan, ref lockHandle);
// Make sure that the item is already locked and the saved LockHandle is used
// Unlock locked item using saved LockHandle
cache.Unlock(key, lockHandle);
Warning
NCache will ignore the locks if other overloads of Get
, Insert
, and Remove
methods are called which do not take or use LockHandle
.
Remove Item with LockHandle
The remove method is a basic method that removes the key from the cache and returns the removed object to the client. If a custom object is added to the cache, the remove method will return Object.
The
LockHandle
should be the same which was used initially to lock the item, otherwise, you will get the exception message saying "Item is locked".If an item is not locked, then
LockHandle
is of no use, and its validity is not checked.
The following example gets an item that is previously locked using the LockHandle
and then removes it by the saved LockHandle
from the cache using the Remove API.
Tip
You can monitor/verify removal:
- "Cache Count" Counter in NCache Monitor or PerfMon Counters.
- Using
cache.Contains
after the expiration interval has elapsed. - Using
cache.Count
before and after specifying expiration.
// Specify the key of the item
string key = $"Product:1001";
// Initialize the lockHandle
LockHandle lockHandle = null;
// Set acquireLock flag as true
bool acquireLock = true;
// Specify time span of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);
// Get the item using the lockHandle
Product result = cache.Get<Product>(key, acquireLock, lockSpan, ref lockHandle);
// Removing locked item using saved lockHandle
cache.Remove(key, lockHandle);
// Check if item is successfully removed
if (result != null)
{
if (result is Product)
{
Product product = (Product)result;
}
}
Special Consideration while Using API Locking
NCache provides a set of APIs with and without LockHandle
to fetch/update the cache item. APIs without a LockHandle
ignore item Locking. So you should use all Locking APIs for data manipulation. For example, if an item is locked and you make an update API call that does not take the LockHandle
as an input parameter, then the item will be updated in the cache irrespective of its Locking state.
Important
When using a Locking feature, you should only use API calls that take LockHandle
as parameters. API which does not take lock handles can be used but should be done so with a lot of care so that it does not
affect data integrity.
Note
In case of Eviction/Expiration, NCache ignores locks which means that a locked item can be removed as a result of Expiration or Eviction.
Topology Wise Behavior
- Mirrored and Replicated Topology
In the Mirror Topology, for all lock operations, a lock is acquired on the Active node, and the same LockHandle
is then replicated to the Passive node so that when Passive becomes Active, item will remain locked. Similarly, the unlock call is also replicated to the Passive node to unlock the item from the Passive node.
In the Replicated Topology, the client is connected to one node, and for all lock operations, the LockHandle
is generated which receives client lock operation, and then the same LockHandle
will be replicated to all other nodes for data consistency. Similarly, the unlock operation will also be replicated to all other nodes.
- Partitioned and Partition-Replica Topology
In the Partitioned Topology, LockHandle
is generated and exists on the same node which contains the item, and during state transfer LockHandle
info is also transferred along with the item, in case item moves to another node.
In Partition-Replica Topology, LockHandle
is generated on the active node which contains the item, and same LockHandle
is then replicated to its replica for data consistency and during state transfer. LockHandle
info is also transferred along with the item, in case the item moves to another node.
- Client Cache
In the Client Cache Topology, all lock-based operations are directly performed at the clustered cache which means that LockHandle
is generated and stored at the clustered cache. No Locking related information is maintained in the Client Cache.
Additional Resources
NCache provides a sample application for item Locking on GitHub.
See Also
.NET: Alachisoft.NCache.Runtime.Caching namespace.
Java: com.alachisoft.ncache.runtime.caching namespace.
Python: ncache.runtime.caching class.
Node.js: Cache class.