• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
  • Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Download
  • Client Side API Programming
  • Locks
  • Pessimistic Locking
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Dependency
      • Oracle Dependency
      • OleDB Dependency
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Overview
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Pub/Sub Topics
      • Publish Messages to a Topic
      • Subscribe to a Topic
      • Monitoring Pub/Sub Topics
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • SignalR Core Integration for NCache
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

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 the NCache Community Edition.

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

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
  • 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.
  • 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: Cache, contains, getCount, insert, lock, LockHandle, remove, TimeSpan, unlock.
  • 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: Cache, contains, get_count, remove, LockHandle, unlock, insert, lock, TimeSpan.
  • 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: Cache, contains, getCount, insert, lock, LockHandle, remove, TimeSpan, unlock.
  • Install either of the following NuGet packages in your .NET client application:
    • Enterprise: Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
    • Professional: Install-Package Alachisoft.NCache.Professional.SDK -Version 4.9.1.0
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Web.Caching namespace in your application.
  • To learn more about the NCache Legacy API, please download the NCache 4.9 documents available as a .zip file on the Alachisoft Website.

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 timespan of 10 seconds which means the item will be unlocked automatically after 10 seconds.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// 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 timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);

// Lock the item for a timespan 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
}
// 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 = new LockHandle();

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan =  new TimeSpan(0, 0, 10);

// Lock the item for a timespan of 10 seconds
boolean lockAcquired = cache.lock(key, lockSpan, 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
}
# Precondtion: Cache is already connected
# Item is already added in the cache

# Specify the key of the item
key = "Product:1001"

# Create a new LockHandle
lock_handle = ncache.LockHandle()

# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)

# Lock the item for a timespan of 10 seconds
lock_acquired = cache.lock(key, lock_span, lock_handle)

# Verify if the item is locked successfully
if lock_acquired:
    # Item has been successfully locked
else:
    # Key does not exist
    # Item is already locked with a different LockHandle
// This is an async method
// Precondition: Cache is already connected
// Item is already added in the cache
// Specify the key of the item
var key = "Product:1001";

// Create a new LockHandle
var lockHandle = new ncache.LockHandle();

// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);

// Lock the item for a timespan of 10 seconds
var lockAcquired = await this.cache.lock(key, lockSpan, 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
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = $"Product:1001";

// Create a new LockHandle
LockHandle lockHandle = null;

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);

// Lock the item for a timespan 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 a 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 the LockHandle.

  • If you pass an incorrect or new empty LockHandle while an item is locked or if acquirelock is set to false, then a null value is returned. However, you will get the LockHandle that was used to lock the item previously.

  • If an item is locked and acquirelock is set to false when correct LockHandle 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 it 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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Set acquireLock flag as true
bool acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = TimeSpan.FromSeconds(10);

// Specify the key of the item
string key = $"Product:1001";

// Create a new LockHandle
LockHandle lockHandle = null;

// Lock the item for a timespan 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
}
// Precondition: Cache is already connected
// Specify the key of the item
String key = "Product:1001";

// Set acquireLock flag as true
boolean acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);

// Create a new LockHandle
LockHandle lockHandle = new LockHandle();

// Lock the item for a timespan of 10 seconds
Object result = cache.get(key, acquireLock, lockSpan, lockHandle, Object.class);

// 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
}
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"

# Set acquireLock flag as true
acquire_lock = True

# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)

# Create a new LockHandle
lock_handle = ncache.LockHandle()

# Lock the item for a timespan of 10 seconds
result = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)

# Verify if the item is locked successfully
if result is not None:
    # Item has been successfully locked
else:
    # Key does not exist
    # Item is already locked with a different LockHandle
// Precondition: Cache is already connected
// Specify the key of the item
var key = "Product:1001";

// Set acquireLock flag as true
var acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);

// Create a new LockHandle
var lockHandle = new ncache.LockHandle();

// Lock the item for a timespan of 10 seconds
// CacheItemVersion set to null and Readthrough Options set to null
var result = await this.cache.getCacheItem(key,null,null, acquireLock, lockSpan, 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
}
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

// Specify the key of the item
string key = "Product:1001";

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);

// Create a new LockHandle
LockHandle lockHandle = new LockHandle();

// Lock the item for a timespan of 10 seconds
object result = cache.Get(key, lockSpan, ref lockHandle, true);

if (result != null)
{
    if (result is Product)
    {
        Product product = (Product)result;
    }
}

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 the releaseLock is set to false, you still have to pass the correct Lockhandle to update the item.

  • If an item is not locked, then the LockHandle and releaseLock 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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Specify the key of the item
string key = $"Product:1001";

// Set acquireLock flag as true
bool acquireLock = true;

// Specify timespan 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);
// Precondition: Cache is already connected
// Specify the key of the item
String key = "Product:1001";

// Set acquireLock flag as true
boolean acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);

// Initialize the lockHandle
LockHandle lockHandle = new LockHandle();

CacheItem item = cache.getCacheItem(key, acquireLock, lockSpan, lockHandle);

// Update the value of item
product = item.getValue(Product.class);
product.setUnitsInStock(200);

boolean 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);
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"

# Set acquireLock flag as true
acquire_lock = True

# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)

# Create a new LockHandle
lock_handle = ncache.LockHandle()

# Lock the item for a timespan of 10 seconds
item = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)

# Update the value of item
product = item.get_value(Product)
product.set_units_in_stock(20)

release_lock = 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,  lockhandle=lock_handle, releaselock=release_lock)
// Precondition: Cache is already connected
// This is an async method
// Specify the key of the item
var key = "Product:1001";

// Set acquireLock flag as true
var acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);

// Initialize the lockHandle
var lockHandle = new ncache.LockHandle();

// cacheItemVersion set to null and readThruOptions set to null;
var item = await this.cache.getCacheItem(key,null,null, acquireLock, lockSpan, lockHandle);

// Update the value of item
var product = item.getValue(ncache.JsonDataType.Object);
product.unitsInStock = 200;

var 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
await this.cache.insert(key, item, null, lockHandle, releaseLock);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = "Product:1001";

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);

// Initialize the lockHandle
LockHandle lockHandle = null;

// Lock the item for 10 seconds
cache.Lock(key, TimeSpan.FromSeconds(10), out lockHandle);

// Get the item
object itemObj = cache.Get(key);

// Modify the object
product.UnitsInStock = 200;

// 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, product);

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.

  • .NET
  • Java
  • Python
  • Node.js
  • Legacy API
// Precondition: Cache is already connected
// Specify the key of the item
string key = $"Product:1001";

// Set acquireLock flag as true
bool acquireLock = true;

// Specify timespan 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);
// Precondition: Cache is already connected
// Specify the key of the item
String key = "Product:1001";

// Set acquireLock flag as true
boolean acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);

// Create a new LockHandle
LockHandle lockHandle = new LockHandle();

Object result = cache.get(key, acquireLock, lockSpan, lockHandle, Object.class);

// Make sure that the item is already locked and the saved LockHandle is used
// Unlock locked item using saved LockHandle
cache.unlock(key, lockHandle);
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"

# Set acquireLock flag as true
acquire_lock = True

# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)

# Create a new LockHandle
lock_handle = ncache.LockHandle()

result = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)

# Make sure that the item is already locked and the saved LockHandle is used
# Unlock locked item using saved LockHandle
cache.unlock(key, lock_handle)
// Precondition: Cache is already connected
// This is an async method
// Specify the key of the item
var key = "Product:1001";

// Set acquireLock flag as true
var acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);

// Create a new LockHandle
var lockHandle = new ncache.LockHandle();

// cacheItemVersion set to null and readThruOptions set to null;
var result = await this.cache.getCacheItem(key,null,null,acquireLock,lockSpan,lockHandle);

// Make sure that the item is already locked and the saved LockHandle is used
// Unlock locked item using saved LockHandle
await this.cache.unlock(key, lockHandle);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = "Product:1001";

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockTimeout = TimeSpan.FromSeconds(10);

// Create a new LockHandle
LockHandle lockHandle = null;

// Lock the item explicitly
cache.Lock(key, lockTimeout, out lockHandle);

object item = cache.Get(key);

// Cast and use the item
Product product = item as Product;

// Release the lock
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.
  • .NET
  • Java
  • Python
  • Node.js
// Precondition: Cache is already connected
// 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 timespan 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;
    }
}
// Precondition: Cache is already connected
// Specify the key of the item
String key = "Product:1001";

// Set acquireLock flag as true
boolean acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
TimeSpan lockSpan = new TimeSpan(0, 0, 10);

// Create a new LockHandle
LockHandle lockHandle = new LockHandle();

Object result = cache.get(key, acquireLock, lockSpan, lockHandle, Object.class);

// Removing locked item using saved lockHandle
// cacheItemVersion and writeThruOptions set to null
cache.remove(key, lockHandle, null, null, Object.class);

Object test = cache.get(key, Object.class);

// check if item has been removed
if (test != null)
{
    //Item has not been removed
}
else
{
    // Item has been removed
}
# Precondition: Cache is already connected
# Specify the key of the item
key = "Product:1001"

# Set acquireLock flag as true
acquire_lock = True

# Specify timespan of 10 seconds for which the item remains locked
lock_span = ncache.TimeSpan(None,0,0,10)

# Create a new LockHandle
lock_handle = ncache.LockHandle()

result = cache.get_cacheitem(key, acquirelock=acquire_lock, locktimeout=lock_span, lockhandle=lock_handle)

# Removing locked item using saved lock_handle
cache.remove(key, Product, lockhandle=lock_handle)

test = cache.get_cacheitem(key)

# Check if item has been removed
if test is not None:
    # Item has not been removed
    print("Remove with lock failed")
else:
    # Item has been removed
    print("Remove with lock successful")
// Precondition: Cache is already connected
// This is an async method
// Specify the key of the item
var key = "Product:1001";

// Set acquireLock flag as true
var acquireLock = true;

// Specify timespan of 10 seconds for which the item remains locked
var lockSpan = new ncache.TimeSpan(None,0,0,10);

// Create a new LockHandle
var lockHandle = new ncache.LockHandle();

// CacheItemVersion and ReadThruOptions set to null
var result = await this.cache.getCacheItem(key,null,null, acquireLock, lockSpan, lockHandle, ncache.JsonDataType.Object);

// Removing locked item using saved lockHandle
// cacheItemVersion and writeThruOptions set to null
await this.cache.remove(key,ncache.JsonDataType.Object, lockHandle, null, null);

var test = await this.cache.getCacheItem(key);

// check if item has been removed
if (test != null)
{
    // Item has not been removed
}
else
{
    // Item has been removed
}

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, a lock is first acquired on the active node. After which the same LockHandle is then replicated to the passive node, so that if the passive node becomes active it remains locked. Therefore, the item will remain locked. This is the case for all lock operations. 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, the LockHandle is generated and exists on the same node which contains the item, and during state transfer, the LockHandle information is also transferred along with the item, in case item moves to another node.

In Partition-Replica Topology, the LockHandle is generated on the active node which contains the item, and the same LockHandle is then replicated to its replica for data consistency and during state transfer. The LockHandle information 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.

In This Article
  • When to Use Pessimistic Locking
  • Prerequisites
  • Lock an Item Explicitly
  • Lock an Item During a Get Operation
  • Release Lock with Update Operation
  • Release Lock Explicitly
  • Remove Item with LockHandle
  • Special Consideration while Using API Locking
  • Topology Wise Behavior
  • Additional Resources
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Community
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top