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.
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.
// 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);
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:
// 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);
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
}
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.
// 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);
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
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;
}
}
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();
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.