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

Sets Behavior and Usage in Cache

Note

This feature is only available in the NCache Enterprise Edition.

A HashSet is an unordered data structure that does not contain duplicate values. For example, a HashSet can be used to store the user ID of all users logging into an e-commerce site on a given day. If the user logs in again, the ID is not stored as duplicate values are not allowed.

NCache further enhances HashSet by providing NCache specific features such as Groups, Tags, Expiration, Locking, Dependencies, and more.

Behavior

  • A HashSet can only be of primitive type.
  • HashSets are named. Hence, you need to provide a unique cache key for each HashSet.
  • Null is not a supported value type.
  • Duplicate values are not supported.

Prerequisites

  • .NET/.NET Core
  • Java
  • Scala
  • 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, IDistributedHashSet, IDataTypeManager, CreateHashSet, GetHashSet, StoreUnion, StoreIntersection, StoreDifference, Remove, 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, DistributedHashSet, getDataStructuresManager, createHashSet, getHashSet, storeUnion, storeIntersection, storeDifference, EventType, getEventType, DataStructureDataChangeListener, onDataStructureChanged, DataStructureEventArg, DataTypeEventDataFilter, 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, DistributedHashSet, DataStructureManager, getDataStructuresManager, DataStructureDataChangeListener, onDataStructureChanged, getEventType, getCollectionItem, DataStructureDataChangeListener, onDataStructureChanged, DataStructureEventArg.
  • 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, DistributedHashSet, DataStructureManager, get_data_structures_manager, create_hashset, get_hashset, store_union, store_intersection, store_difference, get_iterator, remove, remove_random, get_event_type, DataTypeEventDataFilter, EventDataFilter.

Create HashSet and Add Data

Note

A set can not contain duplicate values.

The following code sample creates two HashSets of int type in the cache using CreateHashSet for users logging in on Monday and Tuesday. It then adds data to these two HashSets.

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
  • Python
try
{
    // Pre-condition: Cache must be connected

    // Create unique keys for HashSets
    string mondayUsersKey = "MondayUsers";
    string tuesdayUsersKey = "TuesdayUsers";

    // Create HashSets of int type
    IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.CreateHashSet<int>(mondayUsersKey);

    // Add user IDs for Monday
    userSetMonday.Add(1223);
    userSetMonday.Add(34564);
    userSetMonday.Add(3564);
    IDistributedHashSet<int> userSetTuesday = cache.DataTypeManager.CreateHashSet<int>(tuesdayUsersKey);

    // Add userIDs for Tuesday
    UserSetTuesday.Add(4545);
    UserSetTuesday.Add(34564);
    UserSetTuesday.Add(3564);
    UserSetTuesday.Add(7879);

}
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

    // Create unique keys for HashSets
    String mondayUsersKey = "MondayUsers";
    String tuesdayUsersKey = "TuesdayUsers";

    // Create HashSets of int type
    DistributedHashSet userSetMonday = cache.getDataStructuresManager().createHashSet(mondayUsersKey, Integer.class);

    // Add user IDs for Monday
    userSetMonday.add(1223);
    userSetMonday.add(34564);
    userSetMonday.add(3564);
    DistributedHashSet userSetTuesday = cache.getDataStructuresManager().createHashSet(tuesdayUsersKey, Integer.class);

    // Add userIDs for Tuesday
    userSetTuesday.add(4545);
    userSetTuesday.add(34564);
    userSetTuesday.add(3564);
    userSetTuesday.add(7879);

} 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
    // Create unique keys for HashSets
    val mondayUsersKey = "MondayUsers"
    val tuesdayUsersKey = "TuesdayUsers"

    // Create HashSets of int type
    val userSetMonday = cache.getDataStructuresManager.createHashSet(mondayUsersKey, classOf[Integer])

    // Add user IDs for Monday
    userSetMonday.add(1223)
    userSetMonday.add(34564)
    userSetMonday.add(3564)

    val userSetTuesday = cache.getDataStructuresManager.createHashSet(tuesdayUsersKey, classOf[Integer])
    // Add userIDs for Tuesday
    userSetTuesday.add(4545)
    userSetTuesday.add(34564)
    userSetTuesday.add(3564)
    userSetTuesday.add(7879)
} catch {
    case exception: Exception =>
    // Handle any errors
}
try:
    # Pre-condition: Cache is already connected
    # HashSet with this key already exists in cache

    monday_user_key = "MondayUsers"
    tuesday_user_key = "TuesdayUsers"

    # Create HashSets of int type
    user_set_monday = cache.get_data_structures_manager.create_hashset(monday_user_key, int)

    # Add user IDs for Monday
    user_set_monday.add(1223)
    user_set_monday.add(34564)
    user_set_monday.add(3564)

    user_set_tuesday = cache.get_data_structures_manager.create_hashset(tuesday_user_key, int)

    # Add user IDs for Tuesday
    user_set_monday.add(4545)
    user_set_monday.add(34564)
    user_set_monday.add(3564)
    user_set_monday.add(7879)

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.

Perform Union and Intersection on HashSets

NCache also provides support for native HashSet operations such as Union, Intersection, and Difference. The following code example creates three HashSets of the int type that store the Union, Intersection, and Difference of the two HashSets userSetMonday and userSetTuesday created in the previous example:

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

    // Create unique keys for HashSets
    string totalUsersKey = "TotalUsers";
    string weeklyUsersKey = "WeeklyUsers";
    string differenceKey = "Difference";

    // Create HashSets of int type
    IDistributedHashSet<int> userSetTotal = cache.DataTypeManager.CreateHashSet<int>(totalUsersKey);
    IDistributedHashSet<int> userSetWeekly = cache.DataTypeManager.CreateHashSet<int>(weeklyUsersKey);
    IDistributedHashSet<int> userSetDifference = cache.DataTypeManager.CreateHashSet<int>(differenceKey);

     // userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
    userSetMonday.StoreUnion(totalUsersKey, tuesdayUsersKey);

     // userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
    userSetMonday.StoreIntersection(weeklyUsersKey, tuesdayUsersKey);

    // userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
    userSetMonday.StoreDifference(differenceKey, tuesdayUsersKey);

}
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

    // Create unique keys for HashSets
    String totalUsersKey = "TotalUsers";
    String weeklyUsersKey = "WeeklyUsers";
    String differenceKey = "Difference";

    // Create HashSets of int type
    DistributedHashSet userSetTotal = cache.getDataStructuresManager().createHashSet(totalUsersKey, Integer.class);
    DistributedHashSet userSetWeekly = cache.getDataStructuresManager().createHashSet(weeklyUsersKey, Integer.class);
    DistributedHashSet userSetDifference = cache.getDataStructuresManager().createHashSet(differenceKey, Integer.class);

     // userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
    userSetMonday.storeUnion(totalUsersKey, tuesdayUsersKey);

     // userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
    userSetMonday.storeIntersection(weeklyUsersKey, tuesdayUsersKey);

    // userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
    userSetMonday.storeDifference(differenceKey, tuesdayUsersKey);    

} 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
    // Create unique keys for HashSets
    val totalUsersKey = "TotalUsers"
    val weeklyUsersKey = "WeeklyUsers"
    val differenceKey = "Difference"

    // Create HashSets of int type
    val userSetTotal = cache.getDataStructuresManager.createHashSet(totalUsersKey, classOf[Integer])
    val userSetWeekly = cache.getDataStructuresManager.createHashSet(weeklyUsersKey, classOf[Integer])
    val userSetDifference = cache.getDataStructuresManager.createHashSet(differenceKey, classOf[Integer])

    // userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
    userSetMonday.storeUnion(totalUsersKey, tuesdayUsersKey)

    // userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
    userSetMonday.storeIntersection(weeklyUsersKey, tuesdayUsersKey)

    // userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
    userSetMonday.storeDifference(differenceKey, tuesdayUsersKey)
} catch {
    case exception: Exception =>
    // Handle any errors
}
try:
    # Pre-condition: Cache is already connected
    # HashSet with this key already exists in cache

    total_users_key = "TotalUsers"
    weekly_users_key = "WeeklyUsers"
    difference_key = "Difference"

    # Create HashSets of int type
    user_set_total = cache.get_data_structures_manager.create_hashset(total_users_key, int)
    user_set_weekly = cache.get_data_structures_manager.create_hashset(weekly_users_key, int)
    user_set_difference = cache.get_data_structures_manager.create_hashset(difference_key, int)

    # user_set_total will contain unique values from the HashSets total_users_key and tuesday_users_key after union
    user_set_total.store_union(total_users_key, tuesday_users_key)

    # user_set_weekly will contain common values from the HashSets weekly_users_key and tuesday_users_key after intersection
    user_set_weekly.store_intersection(weekly_users_key, tuesday_users_key)

    # user_set_difference will contain the difference between the HashSets difference_key and tuesday_users_key
    user_set_difference.store_difference(difference_key, tuesday_users_key)

except Exception as exp:
    # Handle errors

Fetch HashSet from Cache

You can fetch a HashSet from the cache using GetHashSet which takes a cache key as a parameter. This key is the name of the HashSet, which is specified during HashSet creation.

Warning

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

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

    // HashSet with this key already exists in cache
    string key = "ProductIDSet";

    // Get HashSet and show items of HashSet
    IDistributedHashSet<int> retrievedHashSet = cache.DataTypeManager.GetHashSet<int>(key);
    if (retrievedHashSet != null)
    {
        foreach (var item in retrievedHashSet)
        {
            // Perform operations
        }
    }
    else
    {
       // HashSet does not exist
    }
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if (ex.ErrorCode == NCacheErrorCodes.NOT_A_HASHSET)
    {
        // Item being fetched is not of HashSet type;
        // Cache key corresponds to an item of different data structure
    }
    else if (ex.ErrorCode == NCacheErrorCodes.TYPE_NOT_ALLOWED)
    {
        // The object being fetched is not of primitive type
        // Custom objects are not yet supported
    }
    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

    // HashSet with this key already exists in cache
    String key = "ProductIDSet";

    // Get HashSet and show items of HashSet
    DistributedHashSet retrievedHashSet = cache.getDataStructuresManager().getHashSet(key, Integer.class);
    if (retrievedHashSet != null) {
        for (var item : retrievedHashSet) {
            // Perform operations
        }
    } else {
        // HashSet does not exist
    }
} catch (OperationFailedException ex) {
    if (ex.getErrorCode() == NCacheErrorCodes.NOT_A_HASHSET) {
        // Item being fetched is not of HashSet type;
        // Cache key corresponds to an item of different data structure
    } else if (ex.getErrorCode() == NCacheErrorCodes.TYPE_NOT_ALLOWED) {
        // The object being fetched is not of primitive type
        // Custom objects are not yet supported
    } 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

    // HashSet with this key already exists in cache
    val key = "ProductIDSet"

    // Get hashset and show items of hashset
    val retrievedHashSet = cache.getDataStructuresManager.getHashSet(key, classOf[Integer])

    if (retrievedHashSet != null) {
      for (item <- retrievedHashSet) {
        // Perform operations
      }
    }
    else {
      // HashSet does not exist
    }
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
try:
    # Pre-condition: Cache is already connected
    # HashSet with this key already exists in cache
    key = "ProductIDSet"

    # Get hashset and show items of hashset
    retrieved_hash_set = cache.get_data_structures_manager().get_hashset(key, int)

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

Remove Items from HashSet

Items can be removed from a HashSet either by specifying the item itself or at random. The following code sample removes the users of Monday from the weekly users HashSet (which have already been added to the cache).

Tip

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

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

    // Get existing HashSets
    string userIDMondayKey = "UserIDMonday";
    string userIDWeeklyKey = "UserIDWeekly";
    IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.GetHashSet<int>(userIDMondayKey);
    IDistributedHashSet<int> usersWeekly = cache.DataTypeManager.GetHashSet<int>(userIDWeeklyKey);

    // Remove users of Monday from Weekly HashSet
    var removedItem = usersWeekly.Remove(userSetMonday);
}
catch (OperationFailedException ex)
{
    // NCache specific exception
    if (ex.ErrorCode == NCacheErrorCodes.NOT_A_SET)
    {
        // Item being fetched is not of HashSet type;
        // Cache key corresponds to an item of different data structure
    }
    else if (ex.ErrorCode == NCacheErrorCodes.TYPE_NOT_ALLOWED)
    {
        // The object being fetched is not of primitive type
        // Custom objects are not yet supported
    }
    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

    // Get existing HashSets
    String userIDMondayKey = "UserIDMonday";
    String userIDWeeklyKey = "UserIDWeekly";
    DistributedHashSet userSetMonday = cache.getDataStructuresManager().getHashSet(userIDMondayKey, Integer.class);
    DistributedHashSet usersWeekly = cache.getDataStructuresManager().getHashSet(userIDWeeklyKey, Integer.class);

    // Remove users of Monday from Weekly HashSet
    var removedItem = usersWeekly.remove(userSetMonday);
} catch (OperationFailedException ex) {
    if (ex.getErrorCode() == NCacheErrorCodes.NOT_A_SET) {
        // Item being fetched is not of HashSet type;
        // Cache key corresponds to an item of different data structure
    } else if (ex.getErrorCode() == NCacheErrorCodes.TYPE_NOT_ALLOWED) {
        // The object being fetched is not of primitive type
        // Custom objects are not yet supported
    } 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
    // Get existing HashSets
    val UserIDMondayKey = "UserIDMonday"
    val UserIDWeeklyKey = "UserIDWeekly"

    val userSetMonday = cache.getDataStructuresManager.getHashSet(UserIDMondayKey, classOf[Int])

    val usersWeekly = cache.getDataStructuresManager.getHashSet(UserIDWeeklyKey, classOf[Int])

    // Remove users of Monday from Weekly set
    usersWeekly.remove(userSetMonday)

    // Remove Random users from weekly set
    usersWeekly.removeRandom
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}
try:
    # Pre-condition: Cache must be connected
    # Get existing HashSets
    user_id_monday_key = "UserIDMonday"
    user_id_weekly_key = "UserIDWeekly"

    user_set_monday = cache.get_data_structures_manager().get_hashset(user_id_monday_key, int)

    users_weekly = cache.get_data_structures_manager().get_hashset(user_id_weekly_key, int)

    # Remove users of Monday from Weekly set
    users_weekly.remove(user_set_monday)

    # Remove Random users from weekly set
    users_weekly.remove_random()
except Exception as exp:
    # Handle errors

Event Notifications on HashSet

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

The following code sample registers a cache event of ItemAdded and ItemUpdated as well as registers an event for ItemAdded and ItemUpdated on the set in cache. Once a HashSet is created in the cache, an ItemAdded cache level event is fired. However, once an item is added to the HashSet, an ItemAdded data structure event is fired, and an ItemUpdated cache level event is fired.

Register Event on HashSet Created

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

    // Unique cache key for hashset
    string key = "UserIDMonday";

    // Create hashset 
    IDistributedHashSet<int> hashset = cache.DataTypeManager.CreateHashSet<int>(key);

    // Register ItemAdded, ItemUpdated, ItemRemoved events on HashSet created
    // DataTypeNotificationCallback is callback method specified
    hashset.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 hashset
    String key = "UserIDMonday";

    // Create HashSet
    DistributedHashSet<Integer> hashSet = cache.getDataStructuresManager().createHashSet(key, Integer.class);

    // Create EnumSet of event types
    EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded,
            EventType.ItemUpdated, EventType.ItemRemoved);

    // Register ItemAdded, ItemUpdated, ItemRemoved events on HashSet created
    // dataChangeListener is the specified callback method
    DataStructureDataChangeListener dataChangeListener = dataStructureListener.onDataStructureChanged(collectionName, args);
    hashSet.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 set
    val key = "IntSet"

    // Initialize change listener
    val dataStructureListener = SetsDataStructureChangeListener()

    // Create Set of Int type
    val set = cache.getDataStructuresManager.getHashSet(key, classOf[Int])

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

    set.addChangeListener(dataStructureListener, enumSet, DataTypeEventDataFilter.Data)
    // Perform operations
}
catch {
    case exception: Exception => {
      // Handle any 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 hashset
    key = "UserIDMonday"

    # Create hashset
    monday_user_set = cache.get_data_structures_manager().create_hashset(key, int)

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

    monday_user_set.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
  • 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 SetsDataStructureChangeListener 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

    }
  }
}
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 HashSet

A HashSet can be explicitly locked and unlocked to ensure data consistency. The following code sample creates a HashSet 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

    // HashSet exists with key "UserIDMonday" Cache Key
    string key = "UserIDMonday";

    // Get HashSet
    IDistributedHashSet<int> hashset = cache.DataTypeManager.GetHashSet<int>(key);

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

    hashset.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

    // HashSet exists with key "UserIDMonday" Cache Key
    String key = "UserIDMonday";

    // Get HashSet
    DistributedHashSet hashset = cache.getDataStructuresManager().getHashSet(key, Integer.class);

    // Lock HashSet for 10 seconds
    boolean isLocked = hashset.lock(TimeSpan.FromSeconds(10));
    if (isLocked) {
        // HashSet is successfully locked for 10 seconds
        // Unless explicitly unlocked
    } else {
        // HashSet is not locked because either:
        // HashSet is not present in the cache
        // HashSet is already locked
    }
    hashset.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 generic exception like IllegalArgumentException or NullPointerException
}
try {
    // Pre-conditions: Cache is already connected
    // HashSet exists with key "UserIDMonday"
    // Cache Key
    val key = "UserIDMonday"

    // Get hashset
    val hashset = cache.getDataStructuresManager.getHashSet(key, classOf[Int])

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

    if (isLocked) {
      // HashSet is successfully locked for 10 seconds
      // Unless explicitly unlocked
    }
    else {
      // HashSet is not locked because either:
      // HashSet is not present in the cache
      // HashSet is already locked
    }

    hashset.unlock()
}
catch {
    case exception: Exception => {
      // Handle any errors
    }
}

Additional Resources

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

See Also

List Behavior and Usage in Cache
Queue Behavior and Usage in Cache
Dictionary Behavior and Usage in Cache
Counter Behavior and Usage in Cache
Configure Searchable Attributes

Back to top Copyright © 2017 Alachisoft