• Webinars
  • Docs
  • Download
  • Blogs
  • Contact Us
Try Free
Show / Hide Table of Contents

List Behavior and Usage in Cache

Note

This feature is only available in NCache Enterprise Edition.

A list is an unordered data structure where data can be added or removed from the list. For example, lists maintain the products added to a cart for an e-commerce website. Let's suppose a user adds the products Umbrella, Green Apples, and Coffee to the cart. Before making the transaction, the product Green Apples is removed, and a new product Pears is added. This is possible because you can update the list from any point within itself.

NCache further enhances the list data structure by providing NCache specific features such as Groups, Tags, Expiration, Locking, Dependencies, and more. In this scenario, the company wants the cart list to be maintained only as long as the session is active. Hence, expiration can be associated with each list created that is equal to the session timeout value.

Behavior

  • A list can be of any primitive type or custom object.
  • A list of CacheItem and nested lists are not yet supported.
  • Lists can be directly accessed by index.
  • Lists are named. Hence, you need to provide a unique cache key for a list.
  • Null is not a supported value type.
  • Duplicate values are supported.

Prerequisites

  • NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
  • 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, IDistributedList, IDataTypeManager, CreateList, AddRange, InsertAtHead, GetList, RemoveRange, IList, RegisterNotification, DataTypeDataNotificationCallback, EventType, DataTypeEventDataFilter, Lock, 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, DistributedList, getDataStructuresManager, createList, addRange, removeRange, insertAtHead, getList, DataStructureDataChangeListener, onDataStructureChanged, addChangeListener, EventType, getEventType, DataTypeEventDataFilter, DataStructureEventArg, getCollectionItem, lock, 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, DistributedList, DataStructureManager, getDataStructuresManager, DataStructureDataChangeListener, onDataStructureChanged, DataStructureEventArg, getEventType, getCollectionItem.
  • 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, DistributedList, getDataStructuresManager, createList, addRange, getList, insertAtHead, remove, removeRange, DataStructureDataChangeListener, lock, EventType, addChangeListener, DataTypeEventDataFilter , DataStructureEventArg, getEventType, getCollectionItem, unlock, DataStructureDataChangeListener.
  • 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, DistributedList, DataStructureManager, get_data_structures_manager, create_list, add_range, get_list, insert_at_head, get_iterator, remove_range, get_event_type, add_change_listener , DataTypeEventDataFilter, EventDataFilter.

Create List and Add Data

The following code sample shows how a list of Product type can be created in the cache using CreateList against the cache key ProductList. Products are added to the list using Add, and then a new range of products is added to the list using AddRange.

Tip

You can also configure searchable attributes such as Groups/Tags/Named Tags and invalidation attributes such as Expiration/Eviction/Dependency while creating a data structure.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
try
{
    // Pre-condition: Cache must be connected

    // Specify unique cache key for list
    string key = "ProductList";

    // Create list of Product type
    IDistributedList<Product> list = cache.DataTypeManager.CreateList<Product>(key);

    // Get products to add to list
    Product[] products = FetchProducts();

    foreach (var product in products)
    {
        // Add products to list
        list.Add(product);
    }
    // Get new products
    Product[] newProducts = FetchNewProducts();

    // Append list of new Products to existing list
    list.AddRange(newProducts);
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
    {
        // The specified key already exists in cache,
        // Either remove the existing object from cache
        // Or specify another key
    }
    else if (ex.ErrorCode == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES)
    {
        // Data structures cannot be of CacheItem type
        // CacheItems cannot be added in data structures
    }
    else
    {
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try {
    // Pre-condition: Cache must be connected

    // Specify unique cache key for list
    String key = "ProductList";

    // Create a list of Product type
    DistributedList<Product> list = cache.getDataStructuresManager().createList(key, Product.class);

    // Get products to add to list
    Product[] products = fetchProducts();

    for (var product : products) {
        // Add products to list
        list.add(product);
    }

    // Get new products
    Product[] newProducts = fetchNewProducts();

    // Append list of new Products to existing list
    list.addRange(Arrays.asList(newProducts));
} catch (OperationFailedException ex) {
    if (ex.getErrorCode() == NCacheErrorCodes.KEY_ALREADY_EXISTS) {
        // The specified key already exists in cache,
        // Either remove the existing object from cache
        // Or specify another key
    } else if (ex.getErrorCode() == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES) {
        // Data structures cannot be of CacheItem type
        // CacheItems cannot be added in data structures
    } else {
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
} catch (Exception ex) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Pre-condition: Cache must be connected// Pre-condition: Cache must be connected

    // Specify unique cache key for list
    val key = "ProductList"

    // Create list of Product type
    val list = cache.getDataStructuresManager.createList(key, classOf[Product])

    // Get products to add to list
    val products = fetchProducts()

    for (product <- products) { // Add products to list
      list.add(product)
    }

    // Get new products
    val newProducts = fetchNewProducts()

    // Append list of new Products to existing list
    list.addRange(newProducts)
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
// This is an async method
try {
  // Pre-condition: Cache must be connected

  // Specify unique cache key for list
  var key = "ProductList";

  // Create list
  var manager = await this.cache.getDataStructuresManager();
  var list = await manager.createList(key, ncache.JsonDataType.Object);

  // Get products to add to list
  var products = this.fetchProducts();

  for (var product in products) {
    // Add products to list
    list.add(product);
  }
  // Get new products
  var newProducts = this.fetchNewProducts();

  // Append list of new Products to existing list
  list.addRange(newProducts);
} catch (error) {
  // Handle errors
}
try:
    # Pre-condition: Cache must be connected
    # Specify unique cache key for list
    key = "ProductList"

    # Create list
    manager = cache.get_data_structures_manager()

    product_list = manager.create_list(key, Product)

    # Get products to add to list
    products = fetch_products()

    for product in products:
        # Add products to list
        product_list.add(product)

    # Get new products
    new_products = fetch_new_products()

    # Append list of new Products to existing list
    product_list.add_range(new_products)
except Exception as exp:
    # Handle errors
Note

To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Update Items in List

You can update lists and items in them using indexes as the lists can be accessed via index. The following code sample updates a value in an existing list (created in the previous example) using the index. It then gets a sale item and adds it to the first index of the list using InsertAtHead.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
try
{
    // Pre-condition: Cache is already connected

    // "list" is created in previous example
    // Update value of index with updated product
    Product updatedProduct = GetUpdatedProductByID(11);
    list[11] = updatedProduct;

    // Get product on sale to insert at head of List
    Product saleProduct = FetchSaleItem();
    list.InsertAtHead(saleProduct);
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try {
    // Pre-condition: Cache is already connected

    // "list" is created in previous example
    // Update value of index with updated product
    Product updatedProduct = getUpdatedProductByID(11);
    list.add(11, updatedProduct);

    // Get product on sale to insert at head of List
    Product saleProduct = fetchSaleItem();
    list.insertAtHead(saleProduct);
} catch (OperationFailedException ex) {
    // NCache specific exception
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
} catch (Exception ex) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Pre-condition: Cache is already connected
    // "list" is created in previous example
    // Update value of index with updated product
    val updatedProduct = fetchProduct("1001")
    productList.add(11, updatedProduct)

    // Get product on sale to insert at head of List
    val saleProduct = fetchSaleItem()
    productList.insertAtHead(saleProduct)
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
// This is an async method
try {
  // Pre-condition: Cache is already connected

  // "list" is created in previous example
  // Update value of index with updated product
  var updatedProduct = this.getUpdatedProductByID(11);
  list.add(11, updatedProduct);

  // Get product on sale to insert at head of List
  var saleProduct = this.fetchSaleItem();
  list.insertAtHead(fetchSaleItem);
} catch (error) {
  // Handle errors
}
try:
    # Pre-condition: Cache is already connected
    # "product_list" is created in previous example
    # Update value of index with updated product
    updated_product = get_updated_product_by_id(1011)
    product_list .add(updated_product, 1011)

    # Get product on sale to insert at head of List
    sale_product = fetch_sale_item()
    product_list .insert_at_head(sale_product)
except Exception as exp:
    # Handle errors

Fetch List from Cache

You can fetch a list from the cache using GetList that takes a cache key as a parameter. This key is the name of the list specified during list creation.

Warning

If the item being fetched is not of List type, a Type mismatch exception is thrown.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
try
{
    // Pre-condition: Cache is already connected

    // List with this key already exists in cache
    string key = "ProductList";

    // Get list and show items of list
    IDistributedList<Product> retrievedList = cache.DataTypeManager.GetList<Product>(key);

    if (retrievedList != null)
    {
        foreach (var item in retrievedList)
        {
            // Perform operations
        }
    }
    else
    {
       // List does not exist
    }
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if (ex.ErrorCode == NCacheErrorCodes.NOT_A_LIST)
    {
        // Item being fetched is not of List type;
        // Cache key corresponds to an item of different data structure
    }
    else
    {
        // NCache specific exception
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try {
    // Pre-condition: Cache is already connected

    // List with this key already exists in cache
    String key = "ProductList";

    // Get list and show items of list
    DistributedList<Product> retrievedList = cache.getDataStructuresManager().getList(key, Product.class);

    if (retrievedList != null) {
        for (var item : retrievedList) {
            // Perform operations
        }
    } else {
        // List does not exist
    }
} catch (OperationFailedException ex) {
    if (ex.getErrorCode() == NCacheErrorCodes.NOT_A_LIST) {
        // Item being fetched is not of List type;
        // Cache key corresponds to an item of different data structure
    } else {
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
} catch (Exception ex) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Pre-condition: Cache is already connected
    // List with this key already exists in cache
    val key = "ProductList"

    // Get list and show items of list
    val retrievedList = cache.getDataStructuresManager.getList(key, classOf[Product])

    if (retrievedList != null) {
      for (item <- retrievedList) {
        // Perform operations
      }
    }
    else {
      // List does not exist
    }
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
// This is an async method
try {
  // Pre-condition: Cache is already connected
  // List with this key already exists in cache
  var key = "ProductList";

  // Get list and show items of list
  var manager = await this.cache.getDataStructuresManager();
  var retrievedList = await manager.getList(key, ncache.JsonDataType.Object);

  if (retrievedList != null) {
    for (var item in retrievedList) {
      // Perform operations
    }
  } else {
    // List does not exist
  }
} catch (error) {
  // Handle errors
}
 try:
    # Pre-condition: Cache is already connected
    # List with this key already exists in cache
    key = "ProductList"

    # Get list and show items of list
    manager = cache.get_data_structures_manager()
    retrieved_list = manager.get_list(key, Product)

    if retrieved_list is not None:
        for item in retrieved_list.get_iterator():
            # Perform operations
            print(item)
    else:
        # List does not exist
        print("List not found")
except Exception as exp:
    # Handle errors

Remove Items from List

Tip

To remove the whole list from cache, refer to the Remove Data Structures from Cache page.

Individual items or a given range of items can be removed from a list. The following code sample removes an individual item using Remove and a range of items for the expired products using RemoveRange.

Note

If the key specified to be removed does not exist, nothing is returned. You can verify the number of keys returned using the return type of RemoveRange.

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
try
{
    // Pre-condition: Cache is already connected

    // List with this key already exists in cache
    string key = "ProductList";

    // Get list to remove items
    IDistributedList<Product> retrievedList = cache.DataTypeManager.GetList<Product>(key);

    // Get range of out of stock products to be removed
    List<Product> outOfStockProducts = FetchOutOfStockProducts();

    // Remove each item individually from retrievedList
    foreach(Product prod in outOfStockProducts)
    {
        retrievedList.Remove(prod);
    }

    // Get range of discontinued products to be removed
    List<Product> discontinuedProducts = FetchDiscontinuedProducts();

    // Remove this range from retrievedList
    // Number of keys removed is returned
    int itemsRemoved = retrievedList.RemoveRange(discontinuedProducts);
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if (ex.ErrorCode == NCacheErrorCodes.NOT_A_LIST)
    {
        // Item being fetched is not of List type;
        // Cache key corresponds to an item of different data structure
    }
    else
    {
        // NCache specific exception
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try {
    // Pre-condition: Cache is already connected

    // List with this key already exists in cache
    String key = "ProductList";

    // Get list to remove items
    DistributedList<Product> retrievedList = cache.getDataStructuresManager().getList(key, Product.class);

    // Get range of out of stock products to be removed
    List<Product> outOfStockProducts = fetchOutOfStockProducts();

    // Remove an individual item from retrieved list
    for(Product prod : outOfStockProducts)
    {
        retrievedList.remove(prod);
    }

    // Get range of discontinued products to be removed
    List<Product> discontinuedProducts = fetchDiscontinuedProducts();

    // Remove this range from retrievedList
    // Number of keys removed is returned
    int itemsRemoved = retrievedList.removeRange(discontinuedProducts);
} catch (OperationFailedException ex) {
    if (ex.getErrorCode() == NCacheErrorCodes.NOT_A_LIST) {
        // Item being fetched is not of List type;
        // Cache key corresponds to an item of different data structure
    } else {
        // Exception can occur due to:
        // Connection Failures
        // Operation Timeout
        // Operation performed during state transfer
    }
} catch (Exception ex) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Pre-condition: Cache is already connected

    // List with this key already exists in cache
    val key = "ProductList"

    // Get list to remove items
    val retrievedList = cache.getDataStructuresManager.getList(key, classOf[Product])

    // Get range of expired products to be removed
    val itemsToRemove = fetchExpiredProducts()

    //Remove this range from retrievedList
    // Number of keys removed is returned
    val itemsRemoved = retrievedList.removeRange(itemsToRemove)
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
// This is an async method
try {
  // Pre-condition: Cache is already connected

  // List with this key already exists in cache
  var key = "ProductList";

  // Get list to remove items
  var manager = await this.cache.getDataStructuresManager();
  var retrievedList = await manager.getList(key, ncache.JsonDataType.Object);

  // Get range of out of stock products to be removed
  var outOfStockProducts = this.fetchOutOfStockProducts();

  // Remove an individual item from retrieved list
  for(var prod in outOfStockProducts){
      await retrievedList.remove(prod);
  }

  // Get range of discontinued json datatype products to be removed
  var discontinuedProducts = this.fetchDiscontinuedProducts();

  // Remove this range from retrievedList
  // Number of keys removed is returned
  var itemsRemoved = await retrievedList.removeRange(discontinuedProducts);
} catch (error) {
  // Handle errors
}
try:
    # Pre-condition: Cache is already connected
    # List with this key already exists in cache
    key = "ProductList"

    # Get list to remove items
    manager = cache.get_data_structures_manager()
    retrieved_list = manager.get_list(key, Product)

    # Get range of expired products to be removed
    items_to_remove = fetch_expired_products()

    # Remove this range from retrievedList
    # Number of keys removed is returned
    items_removed = retrieved_list.remove_range(collection=items_to_remove)
except Exception as exp:
    # Handle errors

Event Notifications on Lists

You can register cache events, key-based events, and data structure events on a data structure such as a list. For behavior, refer to feature wise behavior.

The following code sample registers a cache event of ItemAdded and ItemUpdated. It also registers an event for ItemAdded and ItemUpdated on the list in the cache. Once you create a list in the cache, an ItemAdded cache level event is fired. However, once you add an item to the list, an ItemAdded data structure event, along with an ItemUpdated cache level event is fired. DataTypeEventDataFilter is specified to quantify the amount of information returned upon an event execution. Events, thus registered, then provide the user with the information based on these data filters.

Register Event on List Created

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
try
{
    // Pre-condition: Cache is connected

    // Unique cache key for list
    string key = "ProductList";

    // Create list of Product type
    IDistributedList<Product> list = cache.DataTypeManager.CreateList<Product>(key);

    // Register ItemAdded, ItemUpdated, ItemRemoved events on list created
    // DataTypeNotificationCallback is callback method specified
    list.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
            EventType.ItemUpdated | EventType.ItemRemoved,
            DataTypeEventDataFilter.Data);

    // Perform operations
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try {
    // Precondition: Cache is already connected

    // Unique cache key for list
    String key = "ProductList";

    // Create list of product type
    DistributedList<Product> list = cache.getDataStructuresManager().createList(key, Product.class);

    // Register ItemAdded, ItemUpdated, ItemRemoved events on list created
    // dataChangeListener is the specified callback method
    DataStructureDataChangeListener dataChangeListener = dataStructureListener.onDataStructureChanged(collectionName, args);
    EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded,
            EventType.ItemUpdated, EventType.ItemRemoved);
    list.addChangeListener(dataChangeListener, enumSet, DataTypeEventDataFilter.Data);

    // Perform operations
} catch (OperationFailedException ex) {
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
} catch (Exception ex) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Precondition: Cache is already connected

    // Unique cache key for list
    val key = "ProductList"

    // Initialize change listener
    val dataStructureListener = DataStructureChangeListener()

    // Create list of product type
    val list = cache.getDataStructuresManager.createList(key, classOf[Nothing])

    // Register ItemAdded, ItemUpdated, ItemRemoved events on list created
    val enumSet = List(EventType.ItemAdded, EventType.ItemUpdated, EventType.ItemRemoved)

    list.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data)
    // Perform operations
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
// This is an async method
try {
  // Precondition: Cache is already connected

  // Unique cache key for list
  var key = "ProductList";

  // Create list
  var list = await this.cache
    .getDataStructuresManager()
    .createList(key, ncache.JsonDataType.Object);

  // Register ItemAdded, ItemUpdated, ItemRemoved events on list created
  // dataChangeListener is the specified callback method
  var dataChangeListener = this.dataStructureListener.onDataStructureChanged(
    collectionName,
    args
  );

  var enumSet = enumSet.of(
    ncache.EventType.ItemAdded,
    ncache.EventType.ItemUpdated,
    ncache.EventType.ItemRemoved
  );

  list.addChangeListener(
    dataChangeListener,
    enumSet,
    ncache.DataTypeEventDataFilter.Data
  );

  // Perform operations
} catch (error) {
  // Handle errors
}
def datastructure_callback_function(collection_name, collection_event_args):
    # Perform Operations
    print("Event Fired for " + str(collection_name))

try:
    # Precondition: Cache is already connected
    # Unique cache key for list
    key = "ProductList"

    # Create list
    product_list = cache.get_data_structures_manager().create_list(key, Product)

    # Register ItemAdded, ItemUpdated, ItemRemoved events on list created
    events_list = [ncache.EventType.ITEM_ADDED, ncache.EventType.ITEM_UPDATED, ncache.EventType.ITEM_REMOVED]

    product_list.add_change_listener(datastructure_callback_function, events_list, ncache.DataTypeEventDataFilter.DATA)

    # Perform operations
except Exception as exp:
    # Handle errors

Specify Callback for Event Notification

  • .NET/.NET Core
  • Java
  • Scala
  • Node.js
  • Python
private void DataTypeDataNotificationCallback(string collectionName, DataTypeEventArg collectionEventArgs)
{
    switch (collectionEventArgs.EventType)
    {
        case EventType.ItemAdded:
            // Item has been added to the collection
        break;
        case EventType.ItemUpdated:
            if (collectionEventArgs.CollectionItem != null)
            {
                // Item has been updated in the collection
                // Perform operations
            }
        break;
        case EventType.ItemRemoved:
            // Item has been removed from the collection
        break;
    }
}
DataStructureDataChangeListener dataStructureListener = new DataStructureDataChangeListener() {
    @Override
    public void onDataStructureChanged(String collection, DataStructureEventArg dataStructureEventArg) {
        switch (dataStructureEventArg.getEventType()) {
            case ItemAdded:
                // Item has been added to the collection
            break;
            case ItemUpdated:
                if (dataStructureEventArg.getCollectionItem() != null) {
                    //Item has been updated in the collection
                    // Perform operations
                }
            break;
            case ItemRemoved:
                //Item has been removed from the collection
            break;
        }
    }
};
class DataStructureChangeListener extends DataStructureDataChangeListener {
  override def onDataStructureChanged(collectionName: String, collectionEventArgs: DataStructureEventArg): Unit = {
    collectionEventArgs.getEventType match {
      case EventType.ItemAdded =>
      // Item has been added to the collection

      case EventType.ItemUpdated =>
        if (collectionEventArgs.getCollectionItem != null) {
          //Item has been updated in the collection
          // perform operations
        }

      case EventType.ItemRemoved =>
      //Item has been removed from the collection

    }
  }
}
dataStructureListener = new ncache.DataStructureDataChangeListener();
{
  function onDataStructureChanged(collection, dataStructureEventArg) {
    switch (dataStructureEventArg.getEventType()) {
        case ncache.EventType.ItemAdded:
            //Item has been added to the collection
        break;
        case ncache.EventType.ItemUpdated:
            if (dataStructureEventArg.getCollectionItem() != null) {
                //Item has been updated in the collection
                // perform operations
            }
        break;
        case ncache.EventType.ItemRemoved:
            //Item has been removed from the collection
        break;
    }
  }
}
def datastructure_callback_function(collection_name: str, collection_event_args: DataStructureEventArg):
    if collection_event_args.get_event_type() is ncache.EventType.ITEM_ADDED:
        # Item has been added to the collection
        print("Item added in " + collection_name)

    elif collection_event_args.get_event_type() is ncache.EventType.ITEM_UPDATED:
        # Item has been updated in the collection
        print("Item updated in " + collection_name)

    elif collection_event_args.get_event_type() is ncache.EventType.ITEM_REMOVED:
        # Item has been removed from the collection
        print("Item removed from " + collection_name)

Locking Lists

Lists can be explicitly locked and unlocked to ensure data consistency. The following code sample creates a list and locks it for a period of 10 seconds using Lock(), and then unlocks it using Unlock().

  • .NET/.NET Core
  • Java
  • Scala
try
{
    // Pre-conditions: Cache is already connected
    // List exists with key "ProductList"
    string key = "ProductList";

    // Get list
    IDistributedList<Product> list = cache.DataTypeManager.GetList<Product>(key);

    // Lock list for 10 seconds
    bool isLocked = list.Lock(TimeSpan.FromSeconds(10));
    if (isLocked)
    {
        // List is successfully locked for 10 seconds
        // Unless explicitly unlocked
    }
    else
    {
        // List is not locked because either:
        // List is not present in the cache
        // List is already locked
    }

    list.Unlock();
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any other generic exception like ArgumentNullException or ArgumentException
}
try {
    // Pre-conditions: Cache is already connected
    // List exists with key "ProductList"
    String key = "ProductList";

    // Get list
    DistributedList<Product> list = cache.getDataStructuresManager().getList(key, Product.class);

    // Lock list for 10 seconds
    boolean isLocked = list.lock(TimeSpan.FromSeconds(10));
    if (isLocked) {
        // List is successfully locked for 10 seconds
        // Unless explicitly unlocked
    } else {
        // List is not locked because either:
        // List is not present in the cache
        // List is already locked
    }
    list.unlock();
} catch (OperationFailedException ex) {
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
} catch (Exception ex) {
    // Any generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Pre-conditions: Cache is already connected
    // List exists with key "ProductList"
    // Cache Key
    val key = "ProductList"

    // Get list
    val list = cache.getDataStructuresManager.getList(key, classOf[Product])

    val isLocked = list.lock(TimeSpan.FromSeconds(10))

    if (isLocked) {
      // List is successfully locked for 10 seconds
      // Unless explicitly unlocked
    }
    else {
      // List is not locked because either:
      // List is not present in the cache
      // List is already locked
    }
    list.unlock()
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}

Additional Resources

NCache provides a sample application for the list data structure on GitHub.

See Also

Queue Behavior and Usage in Cache
Sets Behavior and Usage in Cache
Dictionary Behavior and Usage in Cache
Counter Behavior and Usage in Cache

Back to top Copyright © 2017 Alachisoft