• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

List Behavior and Usage in Cache

A distributed list is an unordered, linearly scalable 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, without impacting performance.

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.

NCache List Behavior and Limitations

Since NCache lists are designed for dynamic scaling, large datasets can be stored in a distributed memory space while still having quick index-based access.

  • 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
  • Java
  • Node.js
  • 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, getDataStructuresManager, createList, addRange, getList, insertAtHead, remove, removeRangeCollection, DataStructureDataChangeListener, lock, EventType, addChangeListener, DataTypeEventDataFilter , DataStructureEventArg, getEventType, getCollectionItem, unlock, DataStructureDataChangeListener.

How to Create a Distributed List and Add Data

CreateList enables applications to create a dedicated distributed collection that supports automatic data invalidation policies such as Expiration or Eviction.

The following code sample shows how a list of Product types 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
  • Java
  • Node.js
// Precondition: Cache is already 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);
// Precondition: Cache is already connected

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

// Create 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));
// This is an async method
// Precondition: Cache is already 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 of 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);
Note

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

How to Update Items in a Distributed 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
  • Java
  • Node.js
// Precondition: 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);
// Precondition: 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);
// This is an async method
// Precondition: 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);

How to Retrieve a List from the Cache

You can fetch a list from the cache using GetList which 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
  • Java
  • Node.js
// Precondition: 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
}
// Precondition: 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
}
// This is an async method
// Precondition: 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
}

How to Remove Items from List

Tip

To remove the whole list from the 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
  • Java
  • Node.js
// Precondition: 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);
// Precondition: 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);
// This is an async method
// Precondition: 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 each item individually from retrievedList
for(const prod of outOfStockProducts){
    await retrievedList.remove(prod);
}

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

// Remove this range from retrievedList
// Number of keys removed is returned
var itemsRemoved = await retrievedList.removeRangeCollection(discontinuedProducts);

How to Register 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. A 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.

How to Register Event on List Created

  • .NET
  • Java
  • Node.js
// Precondition: Cache is already 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
// 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
EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded,
        EventType.ItemUpdated, EventType.ItemRemoved);
list.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data);

// Perform operations
// This is an async method
// Precondition: Cache is already connected

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


var enumSet = [
    ncache.EventType.ItemAdded,
    ncache.EventType.ItemUpdated,
    ncache.EventType.ItemRemoved
    ];

list.addChangeListener(
this.dataStructureListener, // Make sure this is initialized
enumSet,
ncache.DataTypeEventDataFilter.Data
);

// Perform operations

How to Specify Callback for Event Notification

  • .NET
  • Java
  • Node.js
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;
        }
    }
};
onDataStructureChanged(collectionName, eventArg) 
{
  switch (eventArg.getEventType()) 
  {
    case ncache.EventType.ItemAdded:
      // Item has been added to the collection
      break;

    case ncache.EventType.ItemUpdated:
      if (eventArg.getCollectionItem() != null) 
      {
        // Item has been updated in the collection
        // Perform operations
      }
      break;

    case ncache.EventType.ItemRemoved:
      // Item has been removed from the collection
      break;
  }
}

How to Implement Distributed Locking on 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
  • Java
// Precondition: 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();
// Precondition: 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();

Additional Resources

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

See Also

.NET: Alachisoft.NCache.Client.DataTypes namespace.
Java: com.alachisoft.ncache.client.datastructures namespace.
Node.js: DistributedList class.

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • 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 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top