void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args)
{
    _keys.push_front(args.key());
    std::pair<IndexIterator, bool> stat = _keyIndex.insert(std::make_pair(args.key(), _keys.begin()));
    if (!stat.second)
    {
        stat.first->second = _keys.begin();
    }
}

Could someone please explain how this code works? It is from POCO LRUCacheStrategy, which employs a map for implementing LRUCache.

We want to change the cache to store its cached objects to disk on close... can we just add some filestream to the strategy?

Thankful for help!

有帮助吗?

解决方案

Serialize the cache map using something like this and store/read it using the fstream.

其他提示

We want to change the cache to store its cached objects to disk on close

There is no explicit cache close() (and, consequently, no strategy onClose() ) call, but you can easily create your own cache (see below) and automate the persistence in the destructor (Important: make sure to prevent any exceptions from escaping the destructor).

Defining your own cache is straightforward, here's a LRUCache with modified destructor:

template <
    class TKey, 
    class TValue,
    class TMutex = FastMutex, 
    class TEventMutex = FastMutex
> 
class PersistentLRUCache: public Poco::AbstractCache<TKey, TValue, LRUStrategy<TKey, TValue>, TMutex, TEventMutex>
{
public:
    // ...

    ~PersistentLRUCache()
    {
            try {
                    Iterator it = _data.begin();
                    Iterator end = _data.end();
                    for (; it != end; ++it)
                    {
                        // write entries to file
                    }
            } catch (...) { /* log errors */}
    }

    // ...
};

Accessing parent class (protected) members is somewhat "dirty" (would be much better if framework provided begin() and end() accessors to the underlying container; for better or worse, it is allowed and you can take advantage of it.

can we just add some filestream to the strategy?

Adding functionality directly to the framework class means your changes would be overwritten with every new release and you'll to have to re-apply your changes. It is better to define your own cache as shown above, that will shield you from framework changes overwriting your functionality.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top