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

Remove Data from Cache

For large amount of data in cache, there can be some data which turns stale over time or is not needed for further operations by the application. For this, NCache allows removing items from the cache, which frees up space in the cache and ensures data consistency and freshness.

NCache provides two overloads of the Remove function to facilitate removal of objects from the cache. These two overloads take the cache item key(s) as their parameter. While both overloads remove the specified items from the cache, they have difference in their return types which makes their uses unique and more flexible.

bool Remove() void Remove()
Returns the removed object to the application in Template type. Returns nothing.        

bool Remove()

This is a fail safe option, as it allows checking whether the data removed should be really removed or not. In case the object removed is not the one you wanted to remove, the returned object can be added back to the cache.

For example, you want to remove a Product type object from the cache but the key provided is not explanatory to describe whether the object is Product type or not. Here, you can check whether the data removed is of Product data type. If it is not, it means the wrong object has been removed, and you can add it back to the cache.

Another use of this overload can be an e-commerce site which needs to remove the products which have less than 3 units available at the end of each business day. Hence, using this overload will remove the items from the cache, but return the objects back to the application so that a list of products running low on units can be maintained.

void Remove()

This approach is a faster operation compared to bool Remove<T>, as it does not have the added operational cost of fetching the objects and returning them to the application. It can be used when you are sure of the data being removed.

For example, an e-commerce site removes those products which have been marked as "discontinued" in the data source but are still residing in the cache. In such a scenario, using this overload will be more efficient as the application does not require keeping track of the products which are no longer available.

Remove Operation Behavior

  • Data can be removed from NCache either as a single item, bulk of items or asynchronously.

  • bool Remove<T> will return the removed object to the application. If the keys specified do not exist, null will be returned and no exception will be thrown.

  • void Remove will return nothing to the application. If the keys specified do not exist, no exception will be thrown.

  • In advanced cases, if data source is configured, data removal will occur in cache as well as data source. For more details, you can refer to the chapter Data Source Providers.

Note

To use Maven packages for NCache Professional Edition, change the <artifactId> as shown below: <artifactId>ncache-professional-client</artifactId>

Pre-requisites

  • .NET/.NET Core
  • Java
  • Node.js
  • Install the following NuGet package in your application.
    • Alachisoft.NCache.SDK
  • Include the following namespaces in your application:
    • Alachisoft.NCache.Client.
    • Alachisoft.NCache.Runtime.Exceptions
  • The application must be connected to cache before performing the operation.
  • Cache must be running.
  • For API details refer to: ICache, Count, bool Remove, Contains, void Remove, RemoveBulk(), RemoveAsync()
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Add the following Maven dependencies in your pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <artifactId>ncache-client</artifactId>
    <version>5.2.0</version>
</dependency>
  • Import the following packages in your application:
    • import com.alachisoft.ncache.client.*;
    • import com.alachisoft.ncache.runtime.exceptions.*;
  • The application must be connected to cache before performing the operation.
  • Cache must be running.
  • Make sure that the data being added is serializable.
  • For API details refer to: Cache, getCount, remove, removeBulk()), removeAsync()
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.
  • Include the following modules in your application:
    • const ncache = require('ncache-client')
  • The application must be connected to cache before performing the operation.
  • Cache must be running.
  • For API details refer to: Cache, remove, removeBulk()
  • To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
  • To handle any unseen exceptions, refer to the Troubleshooting section.

Single Object

A single item can be removed from the cache, which is also returned to the application through the Remove() method. For Java, use the Remove() method to remove the object from the cache.

Important

If the item does not exist in cache, null is returned.

Tip

One quick way to verify whether item has been removed, is to use either properties of the Cache class:

  • Count returns the number of items present in the cache.
  • Contains verifies if a specified key exists in the cache.

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

The following example removes the item corresponding to the specified key and casts the returned object into a Product object to check whether the object is of Product type. If not, it is added back to the cache.

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

    // Unique cache key of product to remove
    string key = $"Product:{product.ProductID}";

    // To return item removed
    Product itemRemoved = new Product();

    // Remove specified item
    cache.Remove(key, out itemRemoved);

    // Check if object is returned 
    if (itemRemoved != null)
    {
        // Check if it is of Product type
        if (itemRemoved is Product)
        {
            // Perform operations
        }
        else
        {
            // The object removed was not of Product type
            // Add it back to the cache
            CacheItemVersion ver = cache.Add(key, itemRemoved);
        }
    }
    else
    {
        // Item does not exist in cache
    }
}
catch (OperationFailedException ex)
{
    // 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

    // Get Product from database against given ProductID
    Product product = fetchProductFromDB(1001);

    // Unique cache key of product to remove
    String key = "Product:" + product.getProductID();

    // Remove specified item
    Product removedItem = cache.remove(key,Product.class);

    // Check if object is returned
    if (removedItem != null)
    {
        // Check if it is of Product type
        // Perform operations
    }
    else
    {
        // Item does not exist in cache
    }
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
   // Any generic exception like NullPointerException or IllegalArgumentException
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected

    // Unique cache key of product to remove
    var key = "Product:" + this.product.getProductID();

    // To return item removed
    var itemRemoved = new Product();

    // Remove specified item
    await this.cache.remove(key,itemRemoved);

    // Check if object is returned 

    if (itemRemoved != null)
    {
        // Check if it is of Product type

        if (itemRemoved instanceof Product)
        {
            // Perform operations
        }
        else
        {
            // The object removed was not of Product type      
            // Add it back to the cache
            var ver = await this.cache.add(key, itemRemoved);
        }
    }
    else
    {
        // Item does not exist in cache
    }
}
catch(error)
{
    // Handle errors
}

If you want to save your computational cost, you can use the void Remove function which will not return anything and is much faster than the previous one.

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

    // Unique cache key of product to remove
    string key = $"Product:{product.ProductID}";

    // Remove specified item
    cache.Remove(key);
}
catch (OperationFailedException ex)
{
    // 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

    // Unique cache key of product to remove
    String key = "Product:" + product.getProductID();

    // Get item against key from cache in template type
    Object result = cache.remove(key);
}
catch (Exception ex) 
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
    // Any generic exception
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected
    // Unique cache key of product to remove
    var key = "Product:" + this.product.getProductID();

    // Remove specified item
    await this.cache.remove(key);

}
catch(error)
{
  // Handle errors
}

JsonObject

Note

This feature is only available in NCache Enterprise Edition.

A JsonObject can be removed from the cache using the Remove method. Using this method, you can remove an item and the removed item is returned. Another overload of Remove method removes a JsonObject from the cache and returns nothing.

The following example removes a JsonObject from the cache and returns the removed item.

  • .NET/.NET Core
  • Java
try
{
    // Specify the unique key for JsonObject
    string key = "Product:1001";

    // JsonObject to be returned           
    var jsonObj = new JsonObject();

    // Remove the JsonObject from the cache
    cache.Remove(key, out jsonObj);

    if (jsonObj != null)
    {
        // Check if it is of Product type
        if (jsonObj is JsonObject)
        {
            // Perform operations
        }
        else
        {
            // The object removed was not JsonObject
        }
    }
    else
    {
        // No item removed from the cache
    }
}
catch (OperationFailedException ex)
{
    // 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
{
    // Get Product from database against given ProductID
    Product product = fetchProductFromDB(1001);

    // Generate a unique key for this product
    String key = "Product:" + product.getProductID();

    // Create a new JSON object and set attributes
    // string values need to be added with JsonValue
    JsonObject jsonProduct = new JsonObject();
    jsonProduct.addAttribute("ProductID", new JsonValue(product.getProductID()));
    jsonProduct.addAttribute("ProductName", new JsonValue(product.getProductName()));
    jsonProduct.addAttribute("Category", new JsonValue(product.getCategory()));
    jsonProduct.addAttribute("UnitPrice", new JsonValue(product.getPrice()));
    jsonProduct.addAttribute("UnitsInStock", new JsonValue(product.getUnitsAvailable()));

    cache.insert(key,jsonProduct);

    // Remove the JsonObject from the cache
    JsonObject removedObject = cache.remove(key,JsonObject.class);

    if (removedObject != null)
    {
        // Check if it is of Product type
        // Perform operations
    }
    else
    {
        // No item removed from the cache
    }
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
  // Any generic exception like NullPointerException or IllegalArgumentException
}

Data Structures

Note

This feature is only available in NCache Enterprise Edition.

An existing data type can be removed from the cache using Remove. The following code removes an existing List from cache and returns it to the client. For more detail on supported data structures, please refer to the section Data Structures in Cache.

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

    // Specify key of list to be removed
    string keyToRemove = "ProductList";

    // Create a list to store returned object
    IDistributedList<Product> returnedList = cache.DataTypeManager.CreateList<Product>("ReturnedList");

    // Remove list and return value
    cache.Remove(keyToRemove, out returnedList);
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if (ex.ErrorCode == NCacheErrorCodes.NOT_A_LIST)
    {
        // The type of the corresponding item is not a list
    }
    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 is already connected

    // Specify key of list to be removed
    String keyToRemove = "ProductList";

    // Create a list to store returned object
    DistributedList<Product> returnedList = cache.getDataStructuresManager().createList("ReturnedList");

    // Remove list and return value
    cache.remove(keyToRemove, returnedList);
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if (ex.getErrorCode() == NCacheErrorCodes.NOT_A_LIST)
    {
        // The type of the corresponding item is not a list
    }
    else
    { 
        // Exception can occur due to:
        // Connection Failures 
        // Operation Timeout
        // Operation performed during state transfer
    }
}
catch (Exception ex)
{
    // Any generic exception like NullPointerException or IllegalArgumentException
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected

    // Specify key of list to be removed
    var keyToRemove = "ProductList";

    // Create a list to store returned object
    var list = this.cache.getDataStructuresManager();
    var returnedList = list.createList("Returned List");

    // Remove list and return value
    await this.cache.remove(keyToRemove,returnedList);
}
catch(error)
{
    // Handle errors
}

Bulk Items

NCache provides RemoveBulk() method to remove a bulk of cache items against the specified array of cache keys. This returns a dictionary of the keys and objects removed from the cache. For Java, use the removeBulk() method to remove a bulk of items from the cache.

Important
  • If the specified items exist in cache, a dictionary of the keys and objects removed is returned.
  • If the specified items do not exist in cache, nothing is returned for those items.

Although a bulk operation is executed as a single operation, the failure of operations is treated individually. For example, if a bulk of 100 items is removed from the cache and 20 of those items do not exist in the cache, the remaining 80 items will be removed from the cache and return to the application.

Tip

One quick way to verify whether item has been removed, is to use either properties of the Cache class:

  • Count returns the number of items present in the cache.
  • Contains verifies if a specified key exists in the cache.

The following example removes a bulk of existing cache items, and casts the returned object into Product objects.

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

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

    // Get products to remove
    Product[] products = FetchProductsFromDB();

    // Specify keys to remove from cache 
    string[] keys = new string[products.Length];
    int index = 0;

    foreach (var product in products)
    {
        keys[index] = $"Product:{product.ProductID}";
        index++;
    }

    // Create dictionary to store removed items
    IDictionary<string, Product> removedItems;

    // Remove items
    cache.RemoveBulk(keys, out removedItems);

    // If items have been returned
    if (removedItems.Count > 0)
    {
        foreach (KeyValuePair<string, Product> entry in removedItems)
        {
            if (entry.Value is Product)
            {
                Product product = entry.Value;

                // Save object for future use as Product object
            }
            else
            {
                // Object not of Product class
            }
        }
    }
    else
    {
        // No objects removed
    }
}
catch (OperationFailedException ex)
{
    // 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

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

    // Specify keys to remove from cache
    ArrayList<String> keys = new ArrayList<>(products.length);

    for (Product product : products)
    {
        String key = "Product:" + product.getProductID();
        keys.add(key);
        cache.insert(key , product);
    }

    // Remove items
    java.util.Map<String, Product> removedItems =  cache.removeBulk(keys, Product.class);

    // If items have been returned
    if (removedItems.size() > 0)
    {
        for (java.util.Map.Entry<String, Product> entry : removedItems.entrySet())
        {
            if (entry.getValue() != null)
            {
                Product product = entry.getValue();

                // Save object for future use as Product object
            }
            else
            {
                // Object not of Product class
            }
        }
    }
    else
    {
        // No objects removed
    }
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
   // Any generic exception like NullPointerException or IllegalArgumentException
}
// This is an async method
try
{
    // Pre-condition: Cache is already connected

    // Get Product from database against given ProductID
    var products = await this.fetchProductFromDB();

    // Get keys to fetch from cache 
    var keys = [products.length];
    var index = 0;

    products.forEach(product => {
        keys[index] ="Product:" + this.product.getProductID();
        index++;
    });

    // Get bulk from cache
    var removedItems = await this.cache.removeBulk(keys);

    // Check if any keys have failed to be retrieved

    if(removedItems.size() > 0)
    {
        removedItems.forEach(entry => {

            if(entry.getValue() instanceof Product)
            {
                var prod = entry.getValue();
                // Perform operations according to business logic
            }
            else
            {
                // Object not of Product type
            }
        });
    }
    else
    {
        // No objects removed
    }
}
catch(error)
{
    // Handle errors
}

Asynchronous API

Note

This feature is only available in NCache Enterprise Edition.

Asynchronous operations are performed in the background, so the client does not have to wait for the response from the server to execute further operations. The list of actions to be performed on the cache is maintained in a queue at the client side and a dedicated background thread keeps on sending them to the server side. Hence, all the operations are being executed in a pure asynchronous manner, increasing the efficiency of the client application.

RemoveAsync returns object of the Task class which can further be used according to the business needs of the client application. NCache provides three different status flags to notify the success or failure of the operation. For Java, use the removeAsync method to remove the items from the cache asynchronously.

IsCanceled: Notifies if the RemoveAsync function is canceled.
IsCompleted: Notifies if the RemoveAsync function is completed.
IsFaulted: Notifies if the RemoveAsync function is faulted.

Important
  • Unlike Remove and RemoveBulk, RemoveAsync does not return the removed objects to the application as it is an asynchronous operation.
  • .NET/.NET Core
  • Java
try
{
    // Pre-condition: Cache is already connected

    // Unique cache key of product to remove
    string key = $"Product:{product.ProductID}";

    // Asynchronously remove items from cache
    Task<Product> task = cache.RemoveAsync<Product>(key);

    //This task object can be used as per your business needs
    if (task.IsFaulted)
    {
        // Task completed due to an unhandled exception
    }
}
catch (OperationFailedException ex)
{
    // 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

    // Get Product from database against given ProductID
    Product product = fetchProductFromDB(1001);

    // Unique cache key of product to remove
    String key = "Product:" + product.getProductID();

    // Create a CacheItem
    var cacheItem = new ncache.CacheItem(product);

    cache.insert(key,cacheItem);

    // Asynchronously remove items from cache
    FutureTask<Product> task = cache.<Product>removeAsync(key,Product.class);

    //This task object can be used as per your business needs
    if (task.isDone())
    {
        // Task completed
    }
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like NullPointerException or IllegalArgumentException
}

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

Additional Resources

NCache provides sample application for Basic Operations on GitHub.

See Also

How to Connect to Cache
Add Data to Cache
Update Existing Data in Cache
Retrieve Existing Cache Data
Start Cache

Back to top Copyright © 2017 Alachisoft