ocean.util.container.cache.PriorityCache

A priority cache which stores a limited amount of items defined at the instantiation tine of the class. When the cache is full and a new object is added the item with the least priority gets dropped.

More...

Members

Classes

PriorityCache
class PriorityCache(T)

Stores a maximum number of items keeping only items with the highest priority.

Detailed Description

To create a new cache class you have to specify the maximum of items that can be stored:

const NUM_ITEM = 10;
auto cache = new PriorityCache!(char[])(NUM_ITEM);

To store an item in the cache you should use 'getOrCreate()` method. The method takes a key and a priority value, if the key already exists then the item associated with the key is returned, if it didn't exist then the class will attempt to create to create a new key with the given priority:

auto key = 1;
ulong priority = 20;
bool item_existed_before;
char[]* item = cache.getOrCreate(key, priority, item_existed_before);

if (item)
{
    *item = "ABC";
}
assert(item_existed_before is false);

Notice that if the item already existed then the priority won't be used (but you still can assign the item to a new value) .

ulong no_effect_priority = 70;
item = cache.getOrCreate(key, no_effect_priority, item_existed_before);

if (item)
{
    *item = "DEF";
}
assert(item_existed_before is true);

ulong retrieved_priority;
item = cache.getPriority(key, retrieved_priority);
assert(item !is null);
assert(*item == "DEF");
assert(retrieved_priority == priority); // Not no_effect_priority

Notice that in all the previous example we have always to check if item is not null (even though we call getOrCreate()), if you are using this class directory then there should be no need to check for null as always a new item will be created. If you are using a class which inherits this class then the subclass might override the whenNewAndLeastPriority() method. This method decides which item to keep if the cache is full and the a newly added item has a lower priority than the existing item in the cache with the least priority. If the method decided to keep the current item and not t add the new one then the getOrCreate() method will return null as no item was found or created.

A useful method to be used when the user wants to store an item with a given priority regardless of whether the item is a new item or already existing one but with a different priority is to use getUpdateOrCreate() method:

auto new_priority = 10;
item = cache.getUpdateOrCreate(key, new_priority, item_existed_before);

cache.getPriority(key, retrieved_priority);
assert(item_existed_before is true);
assert(item !is null);
assert(retrieved_priority == new_priority);

Meta

License

Boost Software License Version 1.0. See LICENSE_BOOST.txt for details. Alternatively, this file may be distributed under the terms of the Tango 3-Clause BSD License (see LICENSE_BSD.txt for details).