Queue Behavior and Usage in Cache
A Queue is an ordered data structure that uses the principle of First In First Out (FIFO) behavior. You can use Queues to maintain information being processed at runtime. For example, the application IDs of potential candidates for a company can be stored in a Queue. As the Queue is FIFO in nature, the first candidate to apply will be interviewed first, and so on.
NCache further enhances Queue data structure by providing NCache-specific features such as Groups, Tags, Expiration, Locking, Dependencies, and more. In this scenario, the company can specify a group against a Queue of people who applied for administrative jobs.
Behavior
- A Queue can be of any primitive type or custom object.
- A Queue of
CacheItem
and nested Queues are not yet supported. - Queues are named. Hence, you need to provide a unique cache key for a Queue.
- Null is not a supported value type.
- Duplicate values are 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, IDistributedQueue, IDataTypeManager, Contains, CopyTo, ToArray, Peek, GetQueue, Dequeue, Enqueue, CreateQueue, RegisterNotification, DataTypeDataNotificationCallback, EventType, DataTypeEventDataFilter, Lock, Unlock.
Create Queue and Add Data
The following code sample shows how a Queue of Candidate type can be created in the cache against the cache key CandidateQueue and how items are added to the Queue.
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
// Specify unique cache key for Queue
string key = "CandidateQueue";
// Create Queue of Candidate type
IDistributedQueue<Candidate> queue = cache.DataTypeManager.CreateQueue<Candidate>(key);
Candidate[] candidates = FetchCandidates();
foreach(var candidate in candidates)
{
// Add candidates to Queue
queue.Enqueue(candidate);
}
Fetch and Perform Other Methods on the Queue
The following code sample fetches a Queue from the cache using the GetQueue
method and then checks whether an item exists in the Queue or not using the Contains
method. How to get an item from the beginning of the Queue without removing it using the Peek
method. To copy the entire source Queue to the target array using the CopyTo
method, and to copy this Queue into a one-dimensional array using the ToArray
method.
// Queue with this key already exists in cache
string key = "CandidateQueue";
// Get Queue and show items of Queue
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);
// Get any candidate ID
Candidate candidate = GetCandidateByID(1002);
// Check whether Queue contains the particular candidate or not
if(retrievedQueue.Contains(candidate))
{
// Candidate exists with this ID
}
// List of candidates for the Queue to be copied into
Candidate[] candidates = new Candidate[retrievedQueue.Count];
// Copy the Queue to another array
retrievedQueue.CopyTo(candidates, 0);
// Copy Queue to one-dimensional array
candidates = retrievedQueue.ToArray();
// Get an item at beginning from Queue without removing
Candidate firstCandidate = retrievedQueue.Peek();
Remove Items from the Queue
Items can be removed from the Queue in a FIFO manner. The following code sample removes the first candidate from the Queue.
Tip
To remove the whole Queue from the cache, refer to the Remove Data Structures from Cache page.
// Queue with this key already exists in cache
string key = "CandidateQueue";
IDistributedQueue<Candidate> retrievedQueue = cache.DataTypeManager.GetQueue<Candidate>(key);
// Remove first item of Queue
retrievedQueue.Dequeue();
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Event Notifications on Queues
You can register cache events, key-based events, and data structure events on a data structure such as a Queue. For more details, refer to feature-wise behavior.
Register Event on Queue Created
The following code sample registers a cache event of ItemAdded
and ItemUpdated
as well as registers an event for ItemAdded
and ItemUpdated
on the Queue in the cache. Once a Queue is created in the cache, an ItemAdded
cache level event is fired. However, once an item is added to the Queue, an ItemAdded
data structure event is fired, and an ItemUpdated
cache level event is fired.
// Unique cache key for Queue
string key = "CandidateQueue";
// Create Queue of Candidate type
IDistributedQueue<Candidate> queue = cache.DataTypeManager.CreateQueue<Candidate>(key);
// Register ItemAdded, ItemUpdated, ItemRemoved events on Queue created
// DataTypeNotificationCallback is callback method specified
queue.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
EventType.ItemUpdated | EventType.ItemRemoved,
DataTypeEventDataFilter.Data);
// Perform operations
Specify Callback for Event Notification
The following code sample shows how to specify a callback method to receive notifications for different events, such as when an item is added, updated, or removed from a collection. By handling these events, you can trigger specific actions in response to changes within the cache.
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 Queues
Queues can be explicitly locked and unlocked to ensure data consistency. The following code sample creates a Queue and locks it for a period of 10 seconds using Lock and then unlocks it using Unlock.
// Queue exists with key "CandidateQueue" cache key
string key = "CandidateQueue";
// Get Queue
IDistributedQueue<Candidate> queue = cache.DataTypeManager.GetQueue<Candidate>(key);
// Lock Queue for 10 seconds
bool isLocked = queue.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
// Queue is successfully locked for 10 seconds
// Unless explicitly unlocked
}
else
{
// Queue is not locked because either:
// Queue is not present in the cache
// Queue is already locked
}
queue.Unlock();
Additional Resources
NCache provides a sample application for the Queue data structure on GitHub.
See Also
.NET: Alachisoft.NCache.Client.DataTypes namespace.
Java: com.alachisoft.ncache.client.datastructures namespace.
Python: ncache.client.datastructures class.
Node.js: DistributedQueue class.