Sets Behavior and Usage in Cache
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
- 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, 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.
// Precondition: 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);
// Precondition: 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);
# Precondition: 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)
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
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:
// 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);
// Precondition: 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);
# Precondition: 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)
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.
// 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
}
// Precondition: 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
}
# Precondition: 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")
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).
// 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);
// Precondition: 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);
# Precondition: 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()
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
// 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
// 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
def datastructure_callback_function(collection_name, collection_event_args):
# Perform Operations
print("Event Fired for " + str(collection_name))
# 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
Specify Callback for Event Notification
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;
}
}
};
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.
// 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();
// Precondition: 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();
Additional Resources
NCache provides a sample application for the HashSet data structure on GitHub.
See Also
.NET: Alachisoft.NCache.Client.DataTypes namespace.
Java: com.alachisoft.ncache.client.datastructures namespace.
Python: ncache.client.datastructures class.