AbstractCache.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //
  2. // AbstractCache.h
  3. //
  4. // $Id: //poco/Main/Foundation/include/Poco/AbstractCache.h#17 $
  5. //
  6. // Library: Foundation
  7. // Package: Cache
  8. // Module: AbstractCache
  9. //
  10. // Definition of the AbstractCache class.
  11. //
  12. // Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
  13. // and Contributors.
  14. //
  15. // Permission is hereby granted, free of charge, to any person or organization
  16. // obtaining a copy of the software and accompanying documentation covered by
  17. // this license (the "Software") to use, reproduce, display, distribute,
  18. // execute, and transmit the Software, and to prepare derivative works of the
  19. // Software, and to permit third-parties to whom the Software is furnished to
  20. // do so, all subject to the following:
  21. //
  22. // The copyright notices in the Software and this entire statement, including
  23. // the above license grant, this restriction and the following disclaimer,
  24. // must be included in all copies of the Software, in whole or in part, and
  25. // all derivative works of the Software, unless such copies or derivative
  26. // works are solely in the form of machine-executable object code generated by
  27. // a source language processor.
  28. //
  29. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  30. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  32. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  33. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  34. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  35. // DEALINGS IN THE SOFTWARE.
  36. //
  37. #ifndef Foundation_AbstractCache_INCLUDED
  38. #define Foundation_AbstractCache_INCLUDED
  39. #include "Poco/KeyValueArgs.h"
  40. #include "Poco/ValidArgs.h"
  41. #include "Poco/Mutex.h"
  42. #include "Poco/Exception.h"
  43. #include "Poco/FIFOEvent.h"
  44. #include "Poco/EventArgs.h"
  45. #include "Poco/Delegate.h"
  46. #include "Poco/SharedPtr.h"
  47. #include <map>
  48. #include <set>
  49. #include <cstddef>
  50. namespace Poco {
  51. template <class TKey, class TValue, class TStrategy, class TMutex = FastMutex, class TEventMutex = FastMutex>
  52. class AbstractCache
  53. /// An AbstractCache is the interface of all caches.
  54. {
  55. public:
  56. FIFOEvent<const KeyValueArgs<TKey, TValue >, TEventMutex > Add;
  57. FIFOEvent<const KeyValueArgs<TKey, TValue >, TEventMutex > Update;
  58. FIFOEvent<const TKey, TEventMutex> Remove;
  59. FIFOEvent<const TKey, TEventMutex> Get;
  60. FIFOEvent<const EventArgs, TEventMutex> Clear;
  61. typedef std::map<TKey, SharedPtr<TValue > > DataHolder;
  62. typedef typename DataHolder::iterator Iterator;
  63. typedef typename DataHolder::const_iterator ConstIterator;
  64. typedef std::set<TKey> KeySet;
  65. AbstractCache()
  66. {
  67. initialize();
  68. }
  69. AbstractCache(const TStrategy& strat): _strategy(strat)
  70. {
  71. initialize();
  72. }
  73. virtual ~AbstractCache()
  74. {
  75. uninitialize();
  76. }
  77. void add(const TKey& key, const TValue& val)
  78. /// Adds the key value pair to the cache.
  79. /// If for the key already an entry exists, it will be overwritten.
  80. {
  81. typename TMutex::ScopedLock lock(_mutex);
  82. doAdd(key, val);
  83. }
  84. void update(const TKey& key, const TValue& val)
  85. /// Adds the key value pair to the cache. Note that adding a NULL SharedPtr will fail!
  86. /// If for the key already an entry exists, it will be overwritten.
  87. /// The difference to add is that no remove or add events are thrown in this case,
  88. /// just a simply silent update is performed
  89. /// If the key doesnot exist the behavior is equal to add, ie. an add event is thrown
  90. {
  91. typename TMutex::ScopedLock lock(_mutex);
  92. doUpdate(key, val);
  93. }
  94. void add(const TKey& key, SharedPtr<TValue > val)
  95. /// Adds the key value pair to the cache. Note that adding a NULL SharedPtr will fail!
  96. /// If for the key already an entry exists, it will be overwritten, ie. first a remove event
  97. /// is thrown, then a add event
  98. {
  99. typename TMutex::ScopedLock lock(_mutex);
  100. doAdd(key, val);
  101. }
  102. void update(const TKey& key, SharedPtr<TValue > val)
  103. /// Adds the key value pair to the cache. Note that adding a NULL SharedPtr will fail!
  104. /// If for the key already an entry exists, it will be overwritten.
  105. /// The difference to add is that no remove or add events are thrown in this case,
  106. /// just an Update is thrown
  107. /// If the key doesnot exist the behavior is equal to add, ie. an add event is thrown
  108. {
  109. typename TMutex::ScopedLock lock(_mutex);
  110. doUpdate(key, val);
  111. }
  112. void remove(const TKey& key)
  113. /// Removes an entry from the cache. If the entry is not found,
  114. /// the remove is ignored.
  115. {
  116. typename TMutex::ScopedLock lock(_mutex);
  117. Iterator it = _data.find(key);
  118. doRemove(it);
  119. }
  120. bool has(const TKey& key) const
  121. /// Returns true if the cache contains a value for the key.
  122. {
  123. typename TMutex::ScopedLock lock(_mutex);
  124. return doHas(key);
  125. }
  126. SharedPtr<TValue> get(const TKey& key)
  127. /// Returns a SharedPtr of the value. The SharedPointer will remain valid
  128. /// even when cache replacement removes the element.
  129. /// If for the key no value exists, an empty SharedPtr is returned.
  130. {
  131. typename TMutex::ScopedLock lock(_mutex);
  132. return doGet (key);
  133. }
  134. void clear()
  135. /// Removes all elements from the cache.
  136. {
  137. typename TMutex::ScopedLock lock(_mutex);
  138. doClear();
  139. }
  140. std::size_t size()
  141. /// Returns the number of cached elements
  142. {
  143. typename TMutex::ScopedLock lock(_mutex);
  144. doReplace();
  145. return _data.size();
  146. }
  147. void forceReplace()
  148. /// Forces cache replacement. Note that Poco's cache strategy use for efficiency reason no background thread
  149. /// which periodically triggers cache replacement. Cache Replacement is only started when the cache is modified
  150. /// from outside, i.e. add is called, or when a user tries to access an cache element via get.
  151. /// In some cases, i.e. expire based caching where for a long time no access to the cache happens,
  152. /// it might be desirable to be able to trigger cache replacement manually.
  153. {
  154. typename TMutex::ScopedLock lock(_mutex);
  155. doReplace();
  156. }
  157. std::set<TKey> getAllKeys()
  158. /// Returns a copy of all keys stored in the cache
  159. {
  160. typename TMutex::ScopedLock lock(_mutex);
  161. doReplace();
  162. ConstIterator it = _data.begin();
  163. ConstIterator itEnd = _data.end();
  164. std::set<TKey> result;
  165. for (; it != itEnd; ++it)
  166. result.insert(it->first);
  167. return result;
  168. }
  169. protected:
  170. mutable FIFOEvent<ValidArgs<TKey> > IsValid;
  171. mutable FIFOEvent<KeySet> Replace;
  172. void initialize()
  173. /// Sets up event registration.
  174. {
  175. Add += Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onAdd);
  176. Update += Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onUpdate);
  177. Remove += Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onRemove);
  178. Get += Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onGet);
  179. Clear += Delegate<TStrategy, const EventArgs>(&_strategy, &TStrategy::onClear);
  180. IsValid += Delegate<TStrategy, ValidArgs<TKey> >(&_strategy, &TStrategy::onIsValid);
  181. Replace += Delegate<TStrategy, KeySet>(&_strategy, &TStrategy::onReplace);
  182. }
  183. void uninitialize()
  184. /// Reverts event registration.
  185. {
  186. Add -= Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onAdd );
  187. Update -= Delegate<TStrategy, const KeyValueArgs<TKey, TValue> >(&_strategy, &TStrategy::onUpdate);
  188. Remove -= Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onRemove);
  189. Get -= Delegate<TStrategy, const TKey>(&_strategy, &TStrategy::onGet);
  190. Clear -= Delegate<TStrategy, const EventArgs>(&_strategy, &TStrategy::onClear);
  191. IsValid -= Delegate<TStrategy, ValidArgs<TKey> >(&_strategy, &TStrategy::onIsValid);
  192. Replace -= Delegate<TStrategy, KeySet>(&_strategy, &TStrategy::onReplace);
  193. }
  194. void doAdd(const TKey& key, const TValue& val)
  195. /// Adds the key value pair to the cache.
  196. /// If for the key already an entry exists, it will be overwritten.
  197. {
  198. Iterator it = _data.find(key);
  199. doRemove(it);
  200. KeyValueArgs<TKey, TValue> args(key, val);
  201. Add.notify(this, args);
  202. _data.insert(std::make_pair(key, SharedPtr<TValue>(new TValue(val))));
  203. doReplace();
  204. }
  205. void doAdd(const TKey& key, SharedPtr<TValue>& val)
  206. /// Adds the key value pair to the cache.
  207. /// If for the key already an entry exists, it will be overwritten.
  208. {
  209. Iterator it = _data.find(key);
  210. doRemove(it);
  211. KeyValueArgs<TKey, TValue> args(key, *val);
  212. Add.notify(this, args);
  213. _data.insert(std::make_pair(key, val));
  214. doReplace();
  215. }
  216. void doUpdate(const TKey& key, const TValue& val)
  217. /// Adds the key value pair to the cache.
  218. /// If for the key already an entry exists, it will be overwritten.
  219. {
  220. KeyValueArgs<TKey, TValue> args(key, val);
  221. Iterator it = _data.find(key);
  222. if (it == _data.end())
  223. {
  224. Add.notify(this, args);
  225. _data.insert(std::make_pair(key, SharedPtr<TValue>(new TValue(val))));
  226. }
  227. else
  228. {
  229. Update.notify(this, args);
  230. it->second = SharedPtr<TValue>(new TValue(val));
  231. }
  232. doReplace();
  233. }
  234. void doUpdate(const TKey& key, SharedPtr<TValue>& val)
  235. /// Adds the key value pair to the cache.
  236. /// If for the key already an entry exists, it will be overwritten.
  237. {
  238. KeyValueArgs<TKey, TValue> args(key, *val);
  239. Iterator it = _data.find(key);
  240. if (it == _data.end())
  241. {
  242. Add.notify(this, args);
  243. _data.insert(std::make_pair(key, val));
  244. }
  245. else
  246. {
  247. Update.notify(this, args);
  248. it->second = val;
  249. }
  250. doReplace();
  251. }
  252. void doRemove(Iterator it)
  253. /// Removes an entry from the cache. If the entry is not found
  254. /// the remove is ignored.
  255. {
  256. if (it != _data.end())
  257. {
  258. Remove.notify(this, it->first);
  259. _data.erase(it);
  260. }
  261. }
  262. bool doHas(const TKey& key) const
  263. /// Returns true if the cache contains a value for the key
  264. {
  265. // ask the strategy if the key is valid
  266. ConstIterator it = _data.find(key);
  267. bool result = false;
  268. if (it != _data.end())
  269. {
  270. ValidArgs<TKey> args(key);
  271. IsValid.notify(this, args);
  272. result = args.isValid();
  273. }
  274. return result;
  275. }
  276. SharedPtr<TValue> doGet(const TKey& key)
  277. /// Returns a SharedPtr of the cache entry, returns 0 if for
  278. /// the key no value was found
  279. {
  280. Iterator it = _data.find(key);
  281. SharedPtr<TValue> result;
  282. if (it != _data.end())
  283. {
  284. // inform all strategies that a read-access to an element happens
  285. Get.notify(this, key);
  286. // ask all strategies if the key is valid
  287. ValidArgs<TKey> args(key);
  288. IsValid.notify(this, args);
  289. if (!args.isValid())
  290. {
  291. doRemove(it);
  292. }
  293. else
  294. {
  295. result = it->second;
  296. }
  297. }
  298. return result;
  299. }
  300. void doClear()
  301. {
  302. static EventArgs _emptyArgs;
  303. Clear.notify(this, _emptyArgs);
  304. _data.clear();
  305. }
  306. void doReplace()
  307. {
  308. std::set<TKey> delMe;
  309. Replace.notify(this, delMe);
  310. // delMe contains the to be removed elements
  311. typename std::set<TKey>::const_iterator it = delMe.begin();
  312. typename std::set<TKey>::const_iterator endIt = delMe.end();
  313. for (; it != endIt; ++it)
  314. {
  315. Iterator itH = _data.find(*it);
  316. doRemove(itH);
  317. }
  318. }
  319. TStrategy _strategy;
  320. mutable DataHolder _data;
  321. mutable TMutex _mutex;
  322. private:
  323. AbstractCache(const AbstractCache& aCache);
  324. AbstractCache& operator = (const AbstractCache& aCache);
  325. };
  326. } // namespace Poco
  327. #endif