aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Framework/CnmMemoryCache.cs
diff options
context:
space:
mode:
authorDahlia Trimble2009-06-02 22:42:47 +0000
committerDahlia Trimble2009-06-02 22:42:47 +0000
commitb38be1a7fdf71a7d3c6d6f761590827b1f45483c (patch)
tree2be409eb714dfd93d78e50d8b0def07b8e9758e1 /OpenSim/Framework/CnmMemoryCache.cs
parentThank you kindly, MattSetzer, for a patch that solves a Mantis: (diff)
downloadopensim-SC-b38be1a7fdf71a7d3c6d6f761590827b1f45483c.zip
opensim-SC-b38be1a7fdf71a7d3c6d6f761590827b1f45483c.tar.gz
opensim-SC-b38be1a7fdf71a7d3c6d6f761590827b1f45483c.tar.bz2
opensim-SC-b38be1a7fdf71a7d3c6d6f761590827b1f45483c.tar.xz
Thank you Imaze Rhiano for a patch that implements Cenome Memory Asset Cache (Mantis #3759)
See the files: bin/config-include/GridCommon.ini.example and bin/config-include/StandaloneCommon.ini.example to configure and enable this caching method.
Diffstat (limited to 'OpenSim/Framework/CnmMemoryCache.cs')
-rw-r--r--OpenSim/Framework/CnmMemoryCache.cs1829
1 files changed, 1829 insertions, 0 deletions
diff --git a/OpenSim/Framework/CnmMemoryCache.cs b/OpenSim/Framework/CnmMemoryCache.cs
new file mode 100644
index 0000000..05a71cf
--- /dev/null
+++ b/OpenSim/Framework/CnmMemoryCache.cs
@@ -0,0 +1,1829 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Diagnostics;
32
33namespace OpenSim.Framework
34{
35 /// <summary>
36 /// Cenome memory based cache to store key/value pairs (elements) limited time and/or limited size.
37 /// </summary>
38 /// <typeparam name="TKey">
39 /// The type of keys in the cache.
40 /// </typeparam>
41 /// <typeparam name="TValue">
42 /// The type of values in the dictionary.
43 /// </typeparam>
44 /// <remarks>
45 /// <para>
46 /// Cenome memory cache stores elements to hash table generations. When new element is being added to cache, and new size would exceed
47 /// maximal allowed size or maximal amount of allowed element count, then elements in oldest generation are deleted. Last access time
48 /// is also tracked in generation level - thus it is possible that some elements are staying in cache far beyond their expiration time.
49 /// If elements in older generations are accessed through <see cref="TryGetValue"/> method, they are moved to newest generation.
50 /// </para>
51 /// </remarks>
52 public class CnmMemoryCache<TKey, TValue> : ICnmCache<TKey, TValue>
53 {
54 /// <summary>
55 /// Default maximal count.
56 /// </summary>
57 /// <seealso cref="MaxCount"/>
58 public const int DefaultMaxCount = 4096;
59
60 /// <summary>
61 /// Default maximal size.
62 /// </summary>
63 /// <remarks>
64 /// <para>
65 /// 128MB = 128 * 1024^2 = 134 217 728 bytes.
66 /// </para>
67 /// </remarks>
68 /// <seealso cref="MaxSize"/>
69 public const long DefaultMaxSize = 134217728;
70
71 /// <summary>
72 /// How many operations between time checks.
73 /// </summary>
74 private const int DefaultOperationsBetweenTimeChecks = 40;
75
76 /// <summary>
77 /// Default expiration time.
78 /// </summary>
79 /// <remarks>
80 /// <para>
81 /// 30 minutes.
82 /// </para>
83 /// </remarks>
84 public static readonly TimeSpan DefaultExpirationTime = TimeSpan.FromMinutes( 30.0 );
85
86 /// <summary>
87 /// Minimal allowed expiration time.
88 /// </summary>
89 /// <remarks>
90 /// <para>
91 /// 5 minutes.
92 /// </para>
93 /// </remarks>
94 public static readonly TimeSpan MinExpirationTime = TimeSpan.FromSeconds( 10.0 );
95
96 /// <summary>
97 /// Comparer used to compare element keys.
98 /// </summary>
99 /// <remarks>
100 /// Comparer is initialized by constructor.
101 /// </remarks>
102 /// <seealso cref="CnmMemoryCache{TKey,TValue}"/>
103 public readonly IEqualityComparer<TKey> Comparer;
104
105 /// <summary>
106 /// Expiration time.
107 /// </summary>
108 private TimeSpan m_expirationTime = DefaultExpirationTime;
109
110 /// <summary>
111 /// Generation bucket count.
112 /// </summary>
113 private int m_generationBucketCount;
114
115 /// <summary>
116 /// Generation entry count.
117 /// </summary>
118 private int m_generationElementCount;
119
120 /// <summary>
121 /// Generation max size.
122 /// </summary>
123 private long m_generationMaxSize;
124
125 /// <summary>
126 /// Maximal allowed count of elements.
127 /// </summary>
128 private int m_maxCount;
129
130 /// <summary>
131 /// Maximal size.
132 /// </summary>
133 private long m_maxSize;
134
135 /// <summary>
136 /// New generation.
137 /// </summary>
138 private IGeneration m_newGeneration;
139
140 /// <summary>
141 /// Old generation.
142 /// </summary>
143 private IGeneration m_oldGeneration;
144
145 /// <summary>
146 /// Operations between time check.
147 /// </summary>
148 private int m_operationsBetweenTimeChecks = DefaultOperationsBetweenTimeChecks;
149
150 /// <summary>
151 /// Synchronization root object, should always be private and exists always
152 /// </summary>
153 private readonly object m_syncRoot = new object();
154
155 /// <summary>
156 /// Version of cache.
157 /// </summary>
158 /// <remarks>
159 /// <para>
160 /// Updated every time when cache has been changed (element removed, expired, added, replaced).
161 /// </para>
162 /// </remarks>
163 private int m_version;
164
165 /// <summary>
166 /// Initializes a new instance of the <see cref="CnmMemoryCache{TKey,TValue}"/> class.
167 /// </summary>
168 public CnmMemoryCache()
169 : this( DefaultMaxSize )
170 {
171 }
172
173 /// <summary>
174 /// Initializes a new instance of the <see cref="CnmMemoryCache{TKey,TValue}"/> class.
175 /// </summary>
176 /// <param name="maximalSize">
177 /// Maximal cache size.
178 /// </param>
179 public CnmMemoryCache( long maximalSize )
180 : this( maximalSize, DefaultMaxCount )
181 {
182 }
183
184 /// <summary>
185 /// Initializes a new instance of the <see cref="CnmMemoryCache{TKey,TValue}"/> class.
186 /// </summary>
187 /// <param name="maximalSize">
188 /// Maximal cache size.
189 /// </param>
190 /// <param name="maximalCount">
191 /// Maximal element count.
192 /// </param>
193 public CnmMemoryCache( long maximalSize, int maximalCount )
194 : this( maximalSize, maximalCount, DefaultExpirationTime )
195 {
196 }
197
198 /// <summary>
199 /// Initializes a new instance of the <see cref="CnmMemoryCache{TKey,TValue}"/> class.
200 /// </summary>
201 /// <param name="maximalSize">
202 /// Maximal cache size.
203 /// </param>
204 /// <param name="maximalCount">
205 /// Maximal element count.
206 /// </param>
207 /// <param name="expirationTime">
208 /// Elements expiration time.
209 /// </param>
210 public CnmMemoryCache( long maximalSize, int maximalCount, TimeSpan expirationTime )
211 : this( maximalSize, maximalCount, expirationTime, EqualityComparer<TKey>.Default )
212 {
213 }
214
215 /// <summary>
216 /// Initializes a new instance of the <see cref="CnmMemoryCache{TKey,TValue}"/> class.
217 /// </summary>
218 /// <param name="maximalSize">
219 /// Maximal cache size.
220 /// </param>
221 /// <param name="maximalCount">
222 /// Maximal element count.
223 /// </param>
224 /// <param name="expirationTime">
225 /// Elements expiration time.
226 /// </param>
227 /// <param name="comparer">
228 /// Comparer used for comparing elements.
229 /// </param>
230 /// <exception cref="ArgumentNullException">
231 /// <see cref="comparer"/>is <see langword="null"/> reference.
232 /// </exception>
233 public CnmMemoryCache(
234 long maximalSize,
235 int maximalCount,
236 TimeSpan expirationTime,
237 IEqualityComparer<TKey> comparer )
238 {
239 if( comparer == null )
240 throw new ArgumentNullException( "comparer" );
241
242 if( expirationTime < MinExpirationTime )
243 expirationTime = MinExpirationTime;
244 if( maximalCount < 8 )
245 maximalCount = 8;
246 if( maximalSize < 8 )
247 maximalSize = 8;
248 if( maximalCount > maximalSize )
249 maximalCount = (int) maximalSize;
250
251 Comparer = comparer;
252 m_expirationTime = expirationTime;
253 m_maxSize = maximalSize;
254 m_maxCount = maximalCount;
255
256 Initialize();
257 }
258
259 /// <summary>
260 /// Add element to new generation.
261 /// </summary>
262 /// <param name="bucketIndex">
263 /// The bucket index.
264 /// </param>
265 /// <param name="key">
266 /// The element's key.
267 /// </param>
268 /// <param name="value">
269 /// The element's value.
270 /// </param>
271 /// <param name="size">
272 /// The element's size.
273 /// </param>
274 protected virtual void AddToNewGeneration( int bucketIndex, TKey key, TValue value, long size )
275 {
276 // Add to newest generation
277 if( !m_newGeneration.Set( bucketIndex, key, value, size ) )
278 {
279 // Failed to add new generation
280 RecycleGenerations();
281 m_newGeneration.Set( bucketIndex, key, value, size );
282 }
283
284 m_version++;
285 }
286
287 /// <summary>
288 /// <para>
289 /// Get keys bucket index.
290 /// </para>
291 /// </summary>
292 /// <param name="key">
293 /// <para>
294 /// Key which bucket index is being retrieved.
295 /// </para>
296 /// </param>
297 /// <returns>
298 /// <para>
299 /// Bucket index.
300 /// </para>
301 /// </returns>
302 /// <remarks>
303 /// <para>
304 /// Method uses <see cref="Comparer"/> to calculate <see cref="key"/> hash code.
305 /// </para>
306 /// <para>
307 /// Bucket index is remainder when element key's hash value is divided by bucket count.
308 /// </para>
309 /// <para>
310 /// For example: key's hash is 72, bucket count is 5, element's bucket index is 72 % 5 = 2.
311 /// </para>
312 /// </remarks>
313 protected virtual int GetBucketIndex( TKey key )
314 {
315 return (Comparer.GetHashCode( key ) & 0x7FFFFFFF) % m_generationBucketCount;
316 }
317
318 /// <summary>
319 /// Purge generation from the cache.
320 /// </summary>
321 /// <param name="generation">
322 /// The generation that is purged.
323 /// </param>
324 protected virtual void PurgeGeneration( IGeneration generation )
325 {
326 generation.Clear();
327 m_version++;
328 }
329
330 /// <summary>
331 /// check expired.
332 /// </summary>
333 private void CheckExpired()
334 {
335 // Do this only one in every m_operationsBetweenTimeChecks
336 // Fetching time is using several millisecons - it is better not to do all time.
337 m_operationsBetweenTimeChecks--;
338 if( m_operationsBetweenTimeChecks <= 0 )
339 PurgeExpired();
340 }
341
342 /// <summary>
343 /// Initialize cache.
344 /// </summary>
345 private void Initialize()
346 {
347 m_version++;
348
349 m_generationMaxSize = MaxSize / 2;
350 MaxElementSize = MaxSize / 8;
351 m_generationElementCount = MaxCount / 2;
352
353 // Buckets need to be prime number to get better spread of hash values
354 m_generationBucketCount = PrimeNumberHelper.GetPrime( m_generationElementCount );
355
356 m_newGeneration = new HashGeneration( this );
357 m_oldGeneration = new HashGeneration( this );
358 m_oldGeneration.MakeOld();
359 }
360
361 /// <summary>
362 /// Recycle generations.
363 /// </summary>
364 private void RecycleGenerations()
365 {
366 // Rotate old generation to new generation, new generation to old generation
367 var temp = m_newGeneration;
368 m_newGeneration = m_oldGeneration;
369 m_newGeneration.Clear();
370 m_oldGeneration = temp;
371 m_oldGeneration.MakeOld();
372 }
373
374 #region Nested type: Enumerator
375
376 /// <summary>
377 /// Key and value pair enumerator.
378 /// </summary>
379 private class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
380 {
381 /// <summary>
382 /// Current enumerator.
383 /// </summary>
384 private int m_currentEnumerator = -1;
385
386 /// <summary>
387 /// Enumerators to different generations.
388 /// </summary>
389 private readonly IEnumerator<KeyValuePair<TKey, TValue>>[] m_generationEnumerators =
390 new IEnumerator<KeyValuePair<TKey, TValue>>[2];
391
392 /// <summary>
393 /// Initializes a new instance of the <see cref="Enumerator"/> class.
394 /// </summary>
395 /// <param name="cache">
396 /// The cache.
397 /// </param>
398 public Enumerator( CnmMemoryCache<TKey, TValue> cache )
399 {
400 m_generationEnumerators[ 0 ] = cache.m_newGeneration.GetEnumerator();
401 m_generationEnumerators[ 1 ] = cache.m_oldGeneration.GetEnumerator();
402 }
403
404 #region IEnumerator<KeyValuePair<TKey,TValue>> Members
405
406 /// <summary>
407 /// Gets the element in the collection at the current position of the enumerator.
408 /// </summary>
409 /// <returns>
410 /// The element in the collection at the current position of the enumerator.
411 /// </returns>
412 /// <exception cref="InvalidOperationException">
413 /// The enumerator has reach end of collection or <see cref="MoveNext"/> is not called.
414 /// </exception>
415 public KeyValuePair<TKey, TValue> Current
416 {
417 get
418 {
419 if( m_currentEnumerator == -1 || m_currentEnumerator >= m_generationEnumerators.Length )
420 throw new InvalidOperationException();
421
422 return m_generationEnumerators[ m_currentEnumerator ].Current;
423 }
424 }
425
426 /// <summary>
427 /// Gets the current element in the collection.
428 /// </summary>
429 /// <returns>
430 /// The current element in the collection.
431 /// </returns>
432 /// <exception cref="T:System.InvalidOperationException">
433 /// The enumerator is positioned before the first element of the collection or after the last element.
434 /// </exception><filterpriority>2</filterpriority>
435 object IEnumerator.Current
436 {
437 get { return Current; }
438 }
439
440 /// <summary>
441 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
442 /// </summary>
443 /// <filterpriority>2</filterpriority>
444 public void Dispose()
445 {
446 }
447
448 /// <summary>
449 /// Advances the enumerator to the next element of the collection.
450 /// </summary>
451 /// <returns>
452 /// <see langword="true"/>if the enumerator was successfully advanced to the next element; <see langword="false"/> if the enumerator has passed the end of the collection.
453 /// </returns>
454 /// <exception cref="T:System.InvalidOperationException">
455 /// The collection was modified after the enumerator was created.
456 /// </exception>
457 /// <filterpriority>2</filterpriority>
458 public bool MoveNext()
459 {
460 if( m_currentEnumerator == -1 )
461 m_currentEnumerator = 0;
462
463 while( m_currentEnumerator < m_generationEnumerators.Length )
464 {
465 if( m_generationEnumerators[ m_currentEnumerator ].MoveNext() )
466 return true;
467
468 m_currentEnumerator++;
469 }
470
471 return false;
472 }
473
474 /// <summary>
475 /// Sets the enumerator to its initial position, which is before the first element in the collection.
476 /// </summary>
477 /// <exception cref="T:System.InvalidOperationException">
478 /// The collection was modified after the enumerator was created.
479 /// </exception>
480 /// <filterpriority>2</filterpriority>
481 public void Reset()
482 {
483 foreach( var enumerator in m_generationEnumerators )
484 {
485 enumerator.Reset();
486 }
487
488 m_currentEnumerator = -1;
489 }
490
491 #endregion
492 }
493
494 #endregion
495
496 #region Nested type: HashGeneration
497
498 /// <summary>
499 /// Hash generation class
500 /// </summary>
501 /// <remarks>
502 /// <para>
503 /// Current implementation is based to separated chaining with move-to-front heuristics. Hash generations have fixed
504 /// amount of buckets and it is never rehashed.
505 /// </para>
506 /// <para>
507 /// Read more about hash tables from <a href="http://en.wikipedia.org/wiki/Hash_table">Wiki article</a>.
508 /// </para>
509 /// </remarks>
510 /// <seealso href="http://en.wikipedia.org/wiki/Hash_table"/>
511 private class HashGeneration : IGeneration
512 {
513 /// <summary>
514 /// Index of first element's in element chain.
515 /// </summary>
516 /// <value>
517 /// -1 if there is no element in bucket; otherwise first element's index in the element chain.
518 /// </value>
519 /// <remarks>
520 /// Bucket index is remainder when element key's hash value is divided by bucket count.
521 /// For example: key's hash is 72, bucket count is 5, element's bucket index is 72 % 5 = 2.
522 /// </remarks>
523 private readonly int[] m_buckets;
524
525 /// <summary>
526 /// Cache object.
527 /// </summary>
528 private readonly CnmMemoryCache<TKey, TValue> m_cache;
529
530 /// <summary>
531 /// Generation's element array.
532 /// </summary>
533 /// <seealso cref="Element"/>
534 private readonly Element[] m_elements;
535
536 /// <summary>
537 /// Index to first free element.
538 /// </summary>
539 private int m_firstFreeElement;
540
541 /// <summary>
542 /// Free element count.
543 /// </summary>
544 /// <remarks>
545 /// When generation is cleared or constructed, this is NOT set to element count.
546 /// This is only tracking elements that are removed and are currently free.
547 /// </remarks>
548 private int m_freeCount;
549
550 /// <summary>
551 /// Is this generation "new generation".
552 /// </summary>
553 private bool m_newGeneration;
554
555 /// <summary>
556 /// Next unused entry.
557 /// </summary>
558 private int m_nextUnusedElement;
559
560 /// <summary>
561 /// Initializes a new instance of the <see cref="HashGeneration"/> class.
562 /// </summary>
563 /// <param name="cache">
564 /// The cache.
565 /// </param>
566 public HashGeneration( CnmMemoryCache<TKey, TValue> cache )
567 {
568 m_cache = cache;
569 m_elements = new Element[m_cache.m_generationElementCount];
570 m_buckets = new int[m_cache.m_generationBucketCount];
571 Clear();
572 }
573
574 /// <summary>
575 /// Find element's index
576 /// </summary>
577 /// <param name="bucketIndex">
578 /// The element's bucket index.
579 /// </param>
580 /// <param name="key">
581 /// The element's key.
582 /// </param>
583 /// <param name="moveToFront">
584 /// Move element to front of elements.
585 /// </param>
586 /// <param name="previousIndex">
587 /// The previous element's index.
588 /// </param>
589 /// <returns>
590 /// Element's index, if found from the generation; -1 otherwise (if element is not found the generation).
591 /// </returns>
592 private int FindElementIndex( int bucketIndex, TKey key, bool moveToFront, out int previousIndex )
593 {
594 previousIndex = -1;
595 var elementIndex = m_buckets[ bucketIndex ];
596 while( elementIndex >= 0 )
597 {
598 if( m_cache.Comparer.Equals( key, m_elements[ elementIndex ].Key ) )
599 {
600 // Found match
601 if( moveToFront && previousIndex >= 0 )
602 {
603 // Move entry to front
604 m_elements[ previousIndex ].Next = m_elements[ elementIndex ].Next;
605 m_elements[ elementIndex ].Next = m_buckets[ bucketIndex ];
606 m_buckets[ bucketIndex ] = elementIndex;
607 previousIndex = 0;
608 }
609
610 return elementIndex;
611 }
612
613 previousIndex = elementIndex;
614 elementIndex = m_elements[ elementIndex ].Next;
615 }
616
617 return -1;
618 }
619
620 /// <summary>
621 /// Remove element front the generation.
622 /// </summary>
623 /// <param name="bucketIndex">
624 /// The bucket index.
625 /// </param>
626 /// <param name="entryIndex">
627 /// The element index.
628 /// </param>
629 /// <param name="previousIndex">
630 /// The element's previous index.
631 /// </param>
632 private void RemoveElement( int bucketIndex, int entryIndex, int previousIndex )
633 {
634 if( previousIndex >= 0 )
635 m_elements[ previousIndex ].Next = m_elements[ entryIndex ].Next;
636 else
637 m_buckets[ bucketIndex ] = m_elements[ entryIndex ].Next;
638
639 Size -= m_elements[ entryIndex ].Size;
640 m_elements[ entryIndex ].Value = default(TValue);
641 m_elements[ entryIndex ].Key = default(TKey);
642
643 // Add element to free elements list
644 m_elements[ entryIndex ].Next = m_firstFreeElement;
645 m_firstFreeElement = entryIndex;
646 m_freeCount++;
647 }
648
649 #region Nested type: Element
650
651 /// <summary>
652 /// Element that stores key, next element in chain, size and value.
653 /// </summary>
654 private struct Element
655 {
656 /// <summary>
657 /// Element's key.
658 /// </summary>
659 public TKey Key;
660
661 /// <summary>
662 /// Next element in chain.
663 /// </summary>
664 /// <remarks>
665 /// When element have value (something is stored to it), this is index of
666 /// next element with same bucket index. When element is free, this
667 /// is index of next element in free element's list.
668 /// </remarks>
669 public int Next;
670
671 /// <summary>
672 /// Size of element.
673 /// </summary>
674 /// <value>
675 /// 0 if element is free; otherwise larger than 0.
676 /// </value>
677 public long Size;
678
679 /// <summary>
680 /// Element's value.
681 /// </summary>
682 /// <remarks>
683 /// It is possible that this value is <see langword="null"/> even when element
684 /// have value - element's value is then <see langword="null"/> reference.
685 /// </remarks>
686 public TValue Value;
687
688 /// <summary>
689 /// Gets a value indicating whether element is free or have value.
690 /// </summary>
691 /// <value>
692 /// <see langword="true"/> when element is free; otherwise <see langword="false"/>.
693 /// </value>
694 public bool IsFree
695 {
696 get { return Size == 0; }
697 }
698 }
699
700 #endregion
701
702 #region Nested type: Enumerator
703
704 /// <summary>
705 /// Key value pair enumerator for <see cref="HashGeneration"/> object.
706 /// </summary>
707 private class Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
708 {
709 /// <summary>
710 /// Current element.
711 /// </summary>
712 private KeyValuePair<TKey, TValue> m_current;
713
714 /// <summary>
715 /// Current index.
716 /// </summary>
717 private int m_currentIndex;
718
719 /// <summary>
720 /// Generation that is being enumerated.
721 /// </summary>
722 private readonly HashGeneration m_generation;
723
724 /// <summary>
725 /// Cache version.
726 /// </summary>
727 /// <remarks>
728 /// When cache is change, version number is changed.
729 /// </remarks>
730 /// <seealso cref="CnmMemoryCache{TKey,TValue}.m_version"/>
731 private readonly int m_version;
732
733 /// <summary>
734 /// Initializes a new instance of the <see cref="Enumerator"/> class.
735 /// </summary>
736 /// <param name="generation">
737 /// The generation.
738 /// </param>
739 public Enumerator( HashGeneration generation )
740 {
741 m_generation = generation;
742 m_version = m_generation.m_cache.m_version;
743 }
744
745 #region IEnumerator<KeyValuePair<TKey,TValue>> Members
746
747 /// <summary>
748 /// Gets the element in the collection at the current position of the enumerator.
749 /// </summary>
750 /// <returns>
751 /// The element in the collection at the current position of the enumerator.
752 /// </returns>
753 /// <exception cref="InvalidOperationException">
754 /// The enumerator has reach end of collection or <see cref="MoveNext"/> is not called.
755 /// </exception>
756 public KeyValuePair<TKey, TValue> Current
757 {
758 get
759 {
760 if( m_currentIndex == 0 || m_currentIndex >= m_generation.Count )
761 throw new InvalidOperationException();
762
763 return m_current;
764 }
765 }
766
767 /// <summary>
768 /// Gets the current element in the collection.
769 /// </summary>
770 /// <returns>
771 /// The current element in the collection.
772 /// </returns>
773 /// <exception cref="InvalidOperationException">
774 /// The enumerator is positioned before the first element of the collection or after the last element.
775 /// </exception><filterpriority>2</filterpriority>
776 object IEnumerator.Current
777 {
778 get { return Current; }
779 }
780
781 /// <summary>
782 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
783 /// </summary>
784 /// <filterpriority>2</filterpriority>
785 public void Dispose()
786 {
787 }
788
789 /// <summary>
790 /// Advances the enumerator to the next element of the collection.
791 /// </summary>
792 /// <returns>
793 /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
794 /// </returns>
795 /// <exception cref="InvalidOperationException">
796 /// The collection was modified after the enumerator was created.
797 /// </exception>
798 public bool MoveNext()
799 {
800 if( m_version != m_generation.m_cache.m_version )
801 throw new InvalidOperationException();
802
803 while( m_currentIndex < m_generation.Count )
804 {
805 if( m_generation.m_elements[ m_currentIndex ].IsFree )
806 {
807 m_currentIndex++;
808 continue;
809 }
810
811 m_current = new KeyValuePair<TKey, TValue>( m_generation.m_elements[ m_currentIndex ].Key,
812 m_generation.m_elements[ m_currentIndex ].Value );
813 m_currentIndex++;
814 return true;
815 }
816
817 m_current = new KeyValuePair<TKey, TValue>();
818 return false;
819 }
820
821 /// <summary>
822 /// Sets the enumerator to its initial position, which is before the first element in the collection.
823 /// </summary>
824 /// <exception cref="InvalidOperationException">
825 /// The collection was modified after the enumerator was created.
826 /// </exception>
827 /// <filterpriority>2</filterpriority>
828 public void Reset()
829 {
830 if( m_version != m_generation.m_cache.m_version )
831 throw new InvalidOperationException();
832
833 m_currentIndex = 0;
834 }
835
836 #endregion
837 }
838
839 #endregion
840
841 #region IGeneration Members
842
843 /// <summary>
844 /// Gets or sets a value indicating whether generation was accessed since last time check.
845 /// </summary>
846 public bool AccessedSinceLastTimeCheck { get; set; }
847
848 /// <summary>
849 /// Gets element count in generation.
850 /// </summary>
851 public int Count
852 {
853 get { return m_nextUnusedElement - m_freeCount; }
854 }
855
856 /// <summary>
857 /// Gets or sets generation's expiration time.
858 /// </summary>
859 public DateTime ExpirationTime { get; set; }
860
861 /// <summary>
862 /// Gets or sets size of data stored to generation.
863 /// </summary>
864 public long Size { get; private set; }
865
866 /// <summary>
867 /// Clear all elements from the generation and make generation new again.
868 /// </summary>
869 /// <remarks>
870 /// When generation is new, it is allowed to add new elements to it and
871 /// <see cref="IGeneration.TryGetValue"/>doesn't remove elements from it.
872 /// </remarks>
873 /// <seealso cref="IGeneration.MakeOld"/>
874 public void Clear()
875 {
876 for( var i = m_buckets.Length - 1 ; i >= 0 ; i-- )
877 {
878 m_buckets[ i ] = -1;
879 }
880
881 Array.Clear( m_elements, 0, m_elements.Length );
882 Size = 0;
883 m_firstFreeElement = -1;
884 m_freeCount = 0;
885 m_nextUnusedElement = 0;
886 m_newGeneration = true;
887 ExpirationTime = DateTime.MaxValue;
888 }
889
890 /// <summary>
891 /// Determines whether the <see cref="IGeneration"/> contains an element with the specific key.
892 /// </summary>
893 /// <param name="bucketIndex">
894 /// The bucket index for the <see cref="key"/> to locate in <see cref="IGeneration"/>.
895 /// </param>
896 /// <param name="key">
897 /// The key to locate in the <see cref="IGeneration"/>.
898 /// </param>
899 /// <returns>
900 /// <see langword="true"/>if the <see cref="IGeneration"/> contains an element with the <see cref="key"/>;
901 /// otherwise <see langword="false"/>.
902 /// </returns>
903 public bool Contains( int bucketIndex, TKey key )
904 {
905 int previousIndex;
906 if( FindElementIndex( bucketIndex, key, true, out previousIndex ) == -1 )
907 return false;
908
909 AccessedSinceLastTimeCheck = true;
910 return true;
911 }
912
913 /// <summary>
914 /// Returns an enumerator that iterates through the elements stored <see cref="HashGeneration"/>.
915 /// </summary>
916 /// <returns>
917 /// A <see cref="IEnumerator"/> that can be used to iterate through the <see cref="HashGeneration"/>.
918 /// </returns>
919 /// <filterpriority>1</filterpriority>
920 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
921 {
922 return new Enumerator( this );
923 }
924
925 /// <summary>
926 /// Make from generation old generation.
927 /// </summary>
928 /// <remarks>
929 /// When generation is old, <see cref="IGeneration.TryGetValue"/> hit removes element from the generation.
930 /// </remarks>
931 /// <seealso cref="IGeneration.Clear"/>
932 public void MakeOld()
933 {
934 m_newGeneration = false;
935 }
936
937 /// <summary>
938 /// Remove element associated with the key from the generation.
939 /// </summary>
940 /// <param name="bucketIndex">
941 /// The element's bucket index.
942 /// </param>
943 /// <param name="key">
944 /// The element's key.
945 /// </param>
946 /// <returns>
947 /// <see langword="true"/>, if remove was successful; otherwise <see langword="false"/>.
948 /// </returns>
949 public bool Remove( int bucketIndex, TKey key )
950 {
951 int previousIndex;
952 var entryIndex = FindElementIndex( bucketIndex, key, false, out previousIndex );
953 if( entryIndex != -1 )
954 {
955 RemoveElement( bucketIndex, entryIndex, previousIndex );
956 AccessedSinceLastTimeCheck = true;
957 return true;
958 }
959
960 return false;
961 }
962
963 /// <summary>
964 /// Set or add element to generation.
965 /// </summary>
966 /// <param name="bucketIndex">
967 /// The element's bucket index.
968 /// </param>
969 /// <param name="key">
970 /// The element's key.
971 /// </param>
972 /// <param name="value">
973 /// The element's value.
974 /// </param>
975 /// <param name="size">
976 /// The element's size.
977 /// </param>
978 /// <returns>
979 /// <see langword="true"/>, if setting or adding was successful; otherwise <see langword="false"/>.
980 /// </returns>
981 /// <remarks>
982 /// <para>
983 /// If element was already existing in generation and new element size fits to collection limits,
984 /// then it's value is replaced with new one and size information is updated. If element didn't
985 /// exists in generation before, then generation must have empty space for a new element and
986 /// size must fit generation's limits, before element is added to generation.
987 /// </para>
988 /// </remarks>
989 public bool Set( int bucketIndex, TKey key, TValue value, long size )
990 {
991 Debug.Assert( m_newGeneration, "It is possible to insert new elements only to newest generation." );
992 Debug.Assert( size > 0, "New element size should be more than 0." );
993
994 int previousIndex;
995 var elementIndex = FindElementIndex( bucketIndex, key, true, out previousIndex );
996 if( elementIndex == -1 )
997 {
998 // New key
999 if( Size + size > m_cache.m_generationMaxSize ||
1000 (m_nextUnusedElement == m_cache.m_generationElementCount && m_freeCount == 0) )
1001 {
1002 // Generation is full
1003 return false;
1004 }
1005
1006 // Increase size of generation
1007 Size += size;
1008
1009 // Get first free entry and update free entry list
1010 if( m_firstFreeElement != -1 )
1011 {
1012 // There was entry that was removed
1013 elementIndex = m_firstFreeElement;
1014 m_firstFreeElement = m_elements[ elementIndex ].Next;
1015 m_freeCount--;
1016 }
1017 else
1018 {
1019 // No entries removed so far - just take a last one
1020 elementIndex = m_nextUnusedElement;
1021 m_nextUnusedElement++;
1022 }
1023
1024 Debug.Assert( m_elements[ elementIndex ].IsFree, "Allocated element is not free." );
1025
1026 // Move new entry to front
1027 m_elements[ elementIndex ].Next = m_buckets[ bucketIndex ];
1028 m_buckets[ bucketIndex ] = elementIndex;
1029
1030 // Set key and update count
1031 m_elements[ elementIndex ].Key = key;
1032 }
1033 else
1034 {
1035 // Existing key
1036 if( Size - m_elements[ elementIndex ].Size + size > m_cache.m_generationMaxSize )
1037 {
1038 // Generation is full
1039 // Remove existing element, because generation is going to be recycled to
1040 // old generation and element is stored to new generation
1041 RemoveElement( bucketIndex, elementIndex, previousIndex );
1042 return false;
1043 }
1044
1045 // Update generation's size
1046 Size = Size - m_elements[ elementIndex ].Size + size;
1047 }
1048
1049 // Finally set value and size
1050 m_elements[ elementIndex ].Value = value;
1051 m_elements[ elementIndex ].Size = size;
1052
1053 // Success - key was inserterted to generation
1054 AccessedSinceLastTimeCheck = true;
1055 return true;
1056 }
1057
1058 /// <summary>
1059 /// Try to get element associated with key.
1060 /// </summary>
1061 /// <param name="bucketIndex">
1062 /// The element's bucket index.
1063 /// </param>
1064 /// <param name="key">
1065 /// The element's key.
1066 /// </param>
1067 /// <param name="value">
1068 /// The element's value.
1069 /// </param>
1070 /// <param name="size">
1071 /// The element's size.
1072 /// </param>
1073 /// <returns>
1074 /// <see langword="true"/>, if element was successful retrieved; otherwise <see langword="false"/>.
1075 /// </returns>
1076 /// <remarks>
1077 /// <para>
1078 /// If element is not found from generation then <paramref name="value"/> and <paramref name="size"/>
1079 /// are set to default value (default(TValue) and 0).
1080 /// </para>
1081 /// </remarks>
1082 public bool TryGetValue( int bucketIndex, TKey key, out TValue value, out long size )
1083 {
1084 // Find entry index,
1085 int previousIndex;
1086 var elementIndex = FindElementIndex( bucketIndex, key, m_newGeneration, out previousIndex );
1087 if( elementIndex == -1 )
1088 {
1089 value = default(TValue);
1090 size = 0;
1091 return false;
1092 }
1093
1094 value = m_elements[ elementIndex ].Value;
1095 size = m_elements[ elementIndex ].Size;
1096
1097 if( !m_newGeneration )
1098 {
1099 // Old generation - remove element, because it is moved to new generation
1100 RemoveElement( bucketIndex, elementIndex, previousIndex );
1101 }
1102
1103 AccessedSinceLastTimeCheck = true;
1104 return true;
1105 }
1106
1107 /// <summary>
1108 /// Returns an enumerator that iterates through a collection.
1109 /// </summary>
1110 /// <returns>
1111 /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
1112 /// </returns>
1113 /// <filterpriority>2</filterpriority>
1114 IEnumerator IEnumerable.GetEnumerator()
1115 {
1116 return GetEnumerator();
1117 }
1118
1119 #endregion
1120 }
1121
1122 #endregion
1123
1124 #region Nested type: IGeneration
1125
1126 /// <summary>
1127 /// Cache element generation interface
1128 /// </summary>
1129 /// <remarks>
1130 /// <para>
1131 /// Generation can hold limited count of elements and limited size of data.
1132 /// </para>
1133 /// <para>
1134 /// There are two kind generations: "new generation" and "old generation(s)". All new elements
1135 /// are added to "new generation".
1136 /// </para>
1137 /// </remarks>
1138 protected interface IGeneration : IEnumerable<KeyValuePair<TKey, TValue>>
1139 {
1140 /// <summary>
1141 /// Gets or sets a value indicating whether generation was accessed since last time check.
1142 /// </summary>
1143 bool AccessedSinceLastTimeCheck { get; set; }
1144
1145 /// <summary>
1146 /// Gets element count in generation.
1147 /// </summary>
1148 int Count { get; }
1149
1150 /// <summary>
1151 /// Gets or sets generation's expiration time.
1152 /// </summary>
1153 DateTime ExpirationTime { get; set; }
1154
1155 /// <summary>
1156 /// Gets size of data stored to generation.
1157 /// </summary>
1158 long Size { get; }
1159
1160 /// <summary>
1161 /// Clear all elements from the generation and make generation new again.
1162 /// </summary>
1163 /// <remarks>
1164 /// When generation is new, it is allowed to add new elements to it and
1165 /// <see cref="TryGetValue"/>doesn't remove elements from it.
1166 /// </remarks>
1167 /// <seealso cref="MakeOld"/>
1168 void Clear();
1169
1170 /// <summary>
1171 /// Determines whether the <see cref="IGeneration"/> contains an element with the specific key.
1172 /// </summary>
1173 /// <param name="bucketIndex">
1174 /// The bucket index for the <see cref="key"/> to locate in <see cref="IGeneration"/>.
1175 /// </param>
1176 /// <param name="key">
1177 /// The key to locate in the <see cref="IGeneration"/>.
1178 /// </param>
1179 /// <returns>
1180 /// <see langword="true"/>if the <see cref="IGeneration"/> contains an element with the <see cref="key"/>;
1181 /// otherwise <see langword="false"/>.
1182 /// </returns>
1183 bool Contains( int bucketIndex, TKey key );
1184
1185 /// <summary>
1186 /// Make from generation old generation.
1187 /// </summary>
1188 /// <remarks>
1189 /// When generation is old, <see cref="TryGetValue"/> hit removes element from the generation.
1190 /// </remarks>
1191 /// <seealso cref="Clear"/>
1192 void MakeOld();
1193
1194 /// <summary>
1195 /// Remove element associated with the key from the generation.
1196 /// </summary>
1197 /// <param name="bucketIndex">
1198 /// The element's bucket index.
1199 /// </param>
1200 /// <param name="key">
1201 /// The element's key.
1202 /// </param>
1203 /// <returns>
1204 /// <see langword="true"/>, if remove was successful; otherwise <see langword="false"/>.
1205 /// </returns>
1206 bool Remove( int bucketIndex, TKey key );
1207
1208 /// <summary>
1209 /// Set or add element to generation.
1210 /// </summary>
1211 /// <param name="bucketIndex">
1212 /// The element's bucket index.
1213 /// </param>
1214 /// <param name="key">
1215 /// The element's key.
1216 /// </param>
1217 /// <param name="value">
1218 /// The element's value.
1219 /// </param>
1220 /// <param name="size">
1221 /// The element's size.
1222 /// </param>
1223 /// <returns>
1224 /// <see langword="true"/>, if setting or adding was successful; otherwise <see langword="false"/>.
1225 /// </returns>
1226 /// <remarks>
1227 /// <para>
1228 /// If element was already existing in generation and new element size fits to collection limits,
1229 /// then it's value is replaced with new one and size information is updated. If element didn't
1230 /// exists in generation before, then generation must have empty space for a new element and
1231 /// size must fit generation's limits, before element is added to generation.
1232 /// </para>
1233 /// </remarks>
1234 bool Set( int bucketIndex, TKey key, TValue value, long size );
1235
1236 /// <summary>
1237 /// Try to get element associated with key.
1238 /// </summary>
1239 /// <param name="bucketIndex">
1240 /// The element's bucket index.
1241 /// </param>
1242 /// <param name="key">
1243 /// The element's key.
1244 /// </param>
1245 /// <param name="value">
1246 /// The element's value.
1247 /// </param>
1248 /// <param name="size">
1249 /// The element's size.
1250 /// </param>
1251 /// <returns>
1252 /// <see langword="true"/>, if element was successful retrieved; otherwise <see langword="false"/>.
1253 /// </returns>
1254 /// <remarks>
1255 /// <para>
1256 /// If element is not found from generation then <paramref name="value"/> and <paramref name="size"/>
1257 /// are set to default value (default(TValue) and 0).
1258 /// </para>
1259 /// </remarks>
1260 bool TryGetValue( int bucketIndex, TKey key, out TValue value, out long size );
1261 }
1262
1263 #endregion
1264
1265 #region ICnmCache<TKey,TValue> Members
1266
1267 /// <summary>
1268 /// Gets current count of elements stored to <see cref="ICnmCache{TKey,TValue}"/>.
1269 /// </summary>
1270 /// <remarks>
1271 /// <para>
1272 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count,
1273 /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element.
1274 /// </para>
1275 /// </remarks>
1276 /// <seealso cref="ICnmCache{TKey,TValue}.MaxCount"/>
1277 /// <seealso cref="ICnmCache{TKey,TValue}.IsCountLimited"/>
1278 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1279 /// <seealso cref="ICnmCache{TKey,TValue}.IsTimeLimited"/>
1280 public int Count
1281 {
1282 get { return m_newGeneration.Count + m_oldGeneration.Count; }
1283 }
1284
1285 /// <summary>
1286 /// Gets or sets elements expiration time.
1287 /// </summary>
1288 /// <value>
1289 /// Elements expiration time.
1290 /// </value>
1291 /// <remarks>
1292 /// <para>
1293 /// When element has been stored in <see cref="ICnmCache{TKey,TValue}"/> longer than <see cref="ICnmCache{TKey,TValue}.ExpirationTime"/>
1294 /// and it is not accessed through <see cref="ICnmCache{TKey,TValue}.TryGetValue"/> method or element's value is
1295 /// not replaced by <see cref="ICnmCache{TKey,TValue}.Set"/> method, then it is automatically removed from the
1296 /// <see cref="ICnmCache{TKey,TValue}"/>.
1297 /// </para>
1298 /// <para>
1299 /// It is possible that <see cref="ICnmCache{TKey,TValue}"/> implementation removes element before it's expiration time,
1300 /// because total size or count of elements stored to cache is larger than <see cref="ICnmCache{TKey,TValue}.MaxSize"/> or <see cref="ICnmCache{TKey,TValue}.MaxCount"/>.
1301 /// </para>
1302 /// <para>
1303 /// It is also possible that element stays in cache longer than <see cref="ICnmCache{TKey,TValue}.ExpirationTime"/>.
1304 /// </para>
1305 /// <para>
1306 /// Calling <see cref="ICnmCache{TKey,TValue}.PurgeExpired"/> try to remove all elements that are expired.
1307 /// </para>
1308 /// <para>
1309 /// To disable time limit in cache, set <see cref="ICnmCache{TKey,TValue}.ExpirationTime"/> to <see cref="DateTime.MaxValue"/>.
1310 /// </para>
1311 /// </remarks>
1312 /// <seealso cref="ICnmCache{TKey,TValue}.IsTimeLimited"/>
1313 /// <seealso cref="ICnmCache{TKey,TValue}.IsCountLimited"/>
1314 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1315 /// <seealso cref="ICnmCache{TKey,TValue}.PurgeExpired"/>
1316 /// <seealso cref="ICnmCache{TKey,TValue}.Count"/>
1317 /// <seealso cref="ICnmCache{TKey,TValue}.MaxCount"/>
1318 /// <seealso cref="ICnmCache{TKey,TValue}.MaxSize"/>
1319 /// <seealso cref="ICnmCache{TKey,TValue}.Size"/>
1320 public TimeSpan ExpirationTime
1321 {
1322 get { return m_expirationTime; }
1323
1324 set
1325 {
1326 if( value < MinExpirationTime )
1327 value = MinExpirationTime;
1328
1329 if( m_expirationTime == value )
1330 return;
1331
1332 var now = DateTime.Now;
1333 m_newGeneration.ExpirationTime = (m_newGeneration.ExpirationTime - m_expirationTime) + value;
1334 m_oldGeneration.ExpirationTime = (m_oldGeneration.ExpirationTime - m_expirationTime) + value;
1335 m_expirationTime = value;
1336
1337 PurgeExpired();
1338 }
1339 }
1340
1341 /// <summary>
1342 /// Gets a value indicating whether <see cref="ICnmCache{TKey,TValue}"/> is limiting count of elements.
1343 /// </summary>
1344 /// <value>
1345 /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> count of elements is limited;
1346 /// otherwise, <see langword="false"/>.
1347 /// </value>
1348 /// <remarks>
1349 /// <para>
1350 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count,
1351 /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element.
1352 /// </para>
1353 /// </remarks>
1354 /// <seealso cref="ICnmCache{TKey,TValue}.Count"/>
1355 /// <seealso cref="ICnmCache{TKey,TValue}.MaxCount"/>
1356 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1357 /// <seealso cref="ICnmCache{TKey,TValue}.IsTimeLimited"/>
1358 public bool IsCountLimited
1359 {
1360 get { return true; }
1361 }
1362
1363 /// <summary>
1364 /// Gets a value indicating whether <see cref="ICnmCache{TKey,TValue}"/> is limiting size of elements.
1365 /// </summary>
1366 /// <value>
1367 /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> total size of elements is limited;
1368 /// otherwise, <see langword="false"/>.
1369 /// </value>
1370 /// <remarks>
1371 /// <para>
1372 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements,
1373 /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element.
1374 /// </para>
1375 /// </remarks>
1376 /// <seealso cref="ICnmCache{TKey,TValue}.MaxElementSize"/>
1377 /// <seealso cref="ICnmCache{TKey,TValue}.Size"/>
1378 /// <seealso cref="ICnmCache{TKey,TValue}.MaxSize"/>
1379 /// <seealso cref="ICnmCache{TKey,TValue}.IsCountLimited"/>
1380 /// <seealso cref="ICnmCache{TKey,TValue}.IsTimeLimited"/>
1381 public bool IsSizeLimited
1382 {
1383 get { return true; }
1384 }
1385
1386 /// <summary>
1387 /// Gets a value indicating whether or not access to the <see cref="ICnmCache{TKey,TValue}"/> is synchronized (thread safe).
1388 /// </summary>
1389 /// <value>
1390 /// <see langword="true"/> if access to the <see cref="ICnmCache{TKey,TValue}"/> is synchronized (thread safe);
1391 /// otherwise, <see langword="false"/>.
1392 /// </value>
1393 /// <remarks>
1394 /// <para>
1395 /// To get synchronized (thread safe) access to <see cref="ICnmCache{TKey,TValue}"/> object, use
1396 /// <see cref="CnmSynchronizedCache{TKey,TValue}.Synchronized"/> in <see cref="CnmSynchronizedCache{TKey,TValue}"/> class
1397 /// to retrieve synchronized wrapper for <see cref="ICnmCache{TKey,TValue}"/> object.
1398 /// </para>
1399 /// </remarks>
1400 /// <seealso cref="ICnmCache{TKey,TValue}.SyncRoot"/>
1401 /// <seealso cref="CnmSynchronizedCache{TKey,TValue}"/>
1402 public bool IsSynchronized
1403 {
1404 get { return false; }
1405 }
1406
1407 /// <summary>
1408 /// Gets a value indicating whether elements stored to <see cref="ICnmCache{TKey,TValue}"/> have limited inactivity time.
1409 /// </summary>
1410 /// <value>
1411 /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> has a fixed total size of elements;
1412 /// otherwise, <see langword="false"/>.
1413 /// </value>
1414 /// <remarks>
1415 /// If <see cref="ICnmCache{TKey,TValue}"/> have limited inactivity time and element is not accessed through <see cref="ICnmCache{TKey,TValue}.Set"/>
1416 /// or <see cref="ICnmCache{TKey,TValue}.TryGetValue"/> methods in <see cref="ICnmCache{TKey,TValue}.ExpirationTime"/> , then element is automatically removed from
1417 /// the cache. Depending on implementation of the <see cref="ICnmCache{TKey,TValue}"/>, some of the elements may
1418 /// stay longer in cache.
1419 /// </remarks>
1420 /// <seealso cref="ICnmCache{TKey,TValue}.ExpirationTime"/>
1421 /// <seealso cref="ICnmCache{TKey,TValue}.PurgeExpired"/>
1422 /// <seealso cref="ICnmCache{TKey,TValue}.IsCountLimited"/>
1423 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1424 public bool IsTimeLimited
1425 {
1426 get { return ExpirationTime != TimeSpan.MaxValue; }
1427 }
1428
1429 /// <summary>
1430 /// Gets or sets maximal allowed count of elements that can be stored to <see cref="ICnmCache{TKey,TValue}"/>.
1431 /// </summary>
1432 /// <value>
1433 /// <see cref="int.MaxValue"/>, if <see cref="ICnmCache{TKey,TValue}"/> is not limited by count of elements;
1434 /// otherwise maximal allowed count of elements.
1435 /// </value>
1436 /// <remarks>
1437 /// <para>
1438 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count,
1439 /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element.
1440 /// </para>
1441 /// </remarks>
1442 public int MaxCount
1443 {
1444 get { return m_maxCount; }
1445
1446 set
1447 {
1448 if( value < 8 )
1449 value = 8;
1450 if( m_maxCount == value )
1451 return;
1452
1453 m_maxCount = value;
1454 Initialize();
1455 }
1456 }
1457
1458 /// <summary>
1459 /// <para>Gets maximal allowed element size.</para>
1460 /// </summary>
1461 /// <value>
1462 /// Maximal allowed element size.
1463 /// </value>
1464 /// <remarks>
1465 /// <para>
1466 /// If element's size is larger than <see cref="ICnmCache{TKey,TValue}.MaxElementSize"/>, then element is
1467 /// not added to the <see cref="ICnmCache{TKey,TValue}"/>.
1468 /// </para>
1469 /// </remarks>
1470 /// <seealso cref="ICnmCache{TKey,TValue}.Set"/>
1471 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1472 /// <seealso cref="ICnmCache{TKey,TValue}.Size"/>
1473 /// <seealso cref="ICnmCache{TKey,TValue}.MaxSize"/>
1474 public long MaxElementSize { get; private set; }
1475
1476 /// <summary>
1477 /// Gets or sets maximal allowed total size for elements stored to <see cref="ICnmCache{TKey,TValue}"/>.
1478 /// </summary>
1479 /// <value>
1480 /// Maximal allowed total size for elements stored to <see cref="ICnmCache{TKey,TValue}"/>.
1481 /// </value>
1482 /// <remarks>
1483 /// <para>
1484 /// Normally size is total bytes used by elements in the cache. But it can be any other suitable unit of measure.
1485 /// </para>
1486 /// <para>
1487 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements,
1488 /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element.
1489 /// </para>
1490 /// </remarks>
1491 /// <seealso cref="ICnmCache{TKey,TValue}.MaxElementSize"/>
1492 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1493 /// <seealso cref="ICnmCache{TKey,TValue}.Size"/>
1494 public long MaxSize
1495 {
1496 get { return m_maxSize; }
1497
1498 set
1499 {
1500 if( value < 8 )
1501 value = 8;
1502 if( m_maxSize == value )
1503 return;
1504
1505 m_maxSize = value;
1506 Initialize();
1507 }
1508 }
1509
1510 /// <summary>
1511 /// Gets total size of elements stored to <see cref="ICnmCache{TKey,TValue}"/>.
1512 /// </summary>
1513 /// <value>
1514 /// Total size of elements stored to <see cref="ICnmCache{TKey,TValue}"/>.
1515 /// </value>
1516 /// <remarks>
1517 /// <para>
1518 /// Normally bytes, but can be any suitable unit of measure.
1519 /// </para>
1520 /// <para>
1521 /// Element's size is given when element is added or replaced by <see cref="ICnmCache{TKey,TValue}.Set"/> method.
1522 /// </para>
1523 /// <para>
1524 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements,
1525 /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element.
1526 /// </para>
1527 /// </remarks>
1528 /// <seealso cref="ICnmCache{TKey,TValue}.MaxElementSize"/>
1529 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1530 /// <seealso cref="ICnmCache{TKey,TValue}.MaxSize"/>
1531 /// <seealso cref="ICnmCache{TKey,TValue}.IsCountLimited"/>
1532 /// <seealso cref="ICnmCache{TKey,TValue}.ExpirationTime"/>
1533 public long Size
1534 {
1535 get { return m_newGeneration.Size + m_oldGeneration.Size; }
1536 }
1537
1538 /// <summary>
1539 /// Gets an object that can be used to synchronize access to the <see cref="ICnmCache{TKey,TValue}"/>.
1540 /// </summary>
1541 /// <value>
1542 /// An object that can be used to synchronize access to the <see cref="ICnmCache{TKey,TValue}"/>.
1543 /// </value>
1544 /// <remarks>
1545 /// <para>
1546 /// To get synchronized (thread safe) access to <see cref="ICnmCache{TKey,TValue}"/>, use <see cref="CnmSynchronizedCache{TKey,TValue}"/>
1547 /// method <see cref="CnmSynchronizedCache{TKey,TValue}.Synchronized"/> to retrieve synchronized wrapper interface to
1548 /// <see cref="ICnmCache{TKey,TValue}"/>.
1549 /// </para>
1550 /// </remarks>
1551 /// <seealso cref="ICnmCache{TKey,TValue}.IsSynchronized"/>
1552 /// <seealso cref="CnmSynchronizedCache{TKey,TValue}"/>
1553 public object SyncRoot
1554 {
1555 get { return m_syncRoot; }
1556 }
1557
1558 /// <summary>
1559 /// Removes all elements from the <see cref="ICnmCache{TKey,TValue}"/>.
1560 /// </summary>
1561 /// <seealso cref="ICnmCache{TKey,TValue}.Set"/>
1562 /// <seealso cref="ICnmCache{TKey,TValue}.Remove"/>
1563 /// <seealso cref="ICnmCache{TKey,TValue}.RemoveRange"/>
1564 /// <seealso cref="ICnmCache{TKey,TValue}.TryGetValue"/>
1565 /// <seealso cref="ICnmCache{TKey,TValue}.PurgeExpired"/>
1566 public void Clear()
1567 {
1568 m_newGeneration.Clear();
1569 m_oldGeneration.Clear();
1570 m_oldGeneration.MakeOld();
1571 m_version++;
1572 }
1573
1574 /// <summary>
1575 /// Returns an enumerator that iterates through the elements stored to <see cref="CnmMemoryCache{TKey,TValue}"/>.
1576 /// </summary>
1577 /// <returns>
1578 /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
1579 /// </returns>
1580 /// <filterpriority>1</filterpriority>
1581 public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
1582 {
1583 return new Enumerator( this );
1584 }
1585
1586 /// <summary>
1587 /// Purge expired elements from the <see cref="ICnmCache{TKey,TValue}"/>.
1588 /// </summary>
1589 /// <remarks>
1590 /// <para>
1591 /// Element becomes expired when last access time to it has been longer time than <see cref="ICnmCache{TKey,TValue}.ExpirationTime"/>.
1592 /// </para>
1593 /// <para>
1594 /// Depending on <see cref="ICnmCache{TKey,TValue}"/> implementation, some of expired elements
1595 /// may stay longer than <see cref="ICnmCache{TKey,TValue}.ExpirationTime"/> in the cache.
1596 /// </para>
1597 /// </remarks>
1598 /// <seealso cref="ICnmCache{TKey,TValue}.IsTimeLimited"/>
1599 /// <seealso cref="ICnmCache{TKey,TValue}.ExpirationTime"/>
1600 /// <seealso cref="ICnmCache{TKey,TValue}.Set"/>
1601 /// <seealso cref="ICnmCache{TKey,TValue}.Remove"/>
1602 /// <seealso cref="ICnmCache{TKey,TValue}.RemoveRange"/>
1603 /// <seealso cref="ICnmCache{TKey,TValue}.TryGetValue"/>
1604 /// <seealso cref="ICnmCache{TKey,TValue}.Clear"/>
1605 public void PurgeExpired()
1606 {
1607 m_operationsBetweenTimeChecks = DefaultOperationsBetweenTimeChecks;
1608
1609 var now = DateTime.Now;
1610 if( m_newGeneration.AccessedSinceLastTimeCheck )
1611 {
1612 // New generation has been accessed since last check
1613 // Update it's expiration time.
1614 m_newGeneration.ExpirationTime = now + ExpirationTime;
1615 m_newGeneration.AccessedSinceLastTimeCheck = false;
1616 }
1617 else if( m_newGeneration.ExpirationTime < now )
1618 {
1619 // New generation has been expired.
1620 // --> also old generation must be expired.
1621 PurgeGeneration( m_newGeneration );
1622 PurgeGeneration( m_oldGeneration );
1623 return;
1624 }
1625
1626 if( m_oldGeneration.ExpirationTime < now )
1627 PurgeGeneration( m_oldGeneration );
1628 }
1629
1630 /// <summary>
1631 /// Removes element associated with <paramref name="key"/> from the <see cref="ICnmCache{TKey,TValue}"/>.
1632 /// </summary>
1633 /// <param name="key">
1634 /// The key that is associated with element to remove from the <see cref="ICnmCache{TKey,TValue}"/>.
1635 /// </param>
1636 /// <exception cref="ArgumentNullException">
1637 /// <paramref name="key"/>is <see langword="null"/>.
1638 /// </exception>
1639 /// <seealso cref="ICnmCache{TKey,TValue}.Set"/>
1640 /// <seealso cref="ICnmCache{TKey,TValue}.RemoveRange"/>
1641 /// <seealso cref="ICnmCache{TKey,TValue}.TryGetValue"/>
1642 /// <seealso cref="ICnmCache{TKey,TValue}.Clear"/>
1643 /// <seealso cref="ICnmCache{TKey,TValue}.PurgeExpired"/>
1644 public void Remove( TKey key )
1645 {
1646 if( key == null )
1647 throw new ArgumentNullException( "key" );
1648
1649 var bucketIndex = GetBucketIndex( key );
1650 if( !m_newGeneration.Remove( bucketIndex, key ) )
1651 {
1652 if( !m_oldGeneration.Remove( bucketIndex, key ) )
1653 {
1654 CheckExpired();
1655 return;
1656 }
1657 }
1658
1659 CheckExpired();
1660 m_version++;
1661 }
1662
1663 /// <summary>
1664 /// Removes elements that are associated with one of <paramref name="keys"/> from the <see cref="ICnmCache{TKey,TValue}"/>.
1665 /// </summary>
1666 /// <param name="keys">
1667 /// The keys that are associated with elements to remove from the <see cref="ICnmCache{TKey,TValue}"/>.
1668 /// </param>
1669 /// <exception cref="ArgumentNullException">
1670 /// <paramref name="keys"/>is <see langword="null"/>.
1671 /// </exception>
1672 /// <seealso cref="ICnmCache{TKey,TValue}.Set"/>
1673 /// <seealso cref="ICnmCache{TKey,TValue}.Remove"/>
1674 /// <seealso cref="ICnmCache{TKey,TValue}.TryGetValue"/>
1675 /// <seealso cref="ICnmCache{TKey,TValue}.Clear"/>
1676 /// <seealso cref="ICnmCache{TKey,TValue}.PurgeExpired"/>
1677 public void RemoveRange( IEnumerable<TKey> keys )
1678 {
1679 if( keys == null )
1680 throw new ArgumentNullException( "keys" );
1681
1682 foreach( var key in keys )
1683 {
1684 if( key == null )
1685 continue;
1686
1687 var bucketIndex = GetBucketIndex( key );
1688 if( !m_newGeneration.Remove( bucketIndex, key ) )
1689 m_oldGeneration.Remove( bucketIndex, key );
1690 }
1691
1692 CheckExpired();
1693 m_version++;
1694 }
1695
1696 /// <summary>
1697 /// Add or replace an element with the provided <paramref name="key"/>, <paramref name="value"/> and <paramref name="size"/> to
1698 /// <see cref="ICnmCache{TKey,TValue}"/>.
1699 /// </summary>
1700 /// <param name="key">
1701 /// The object used as the key of the element. Can't be <see langword="null"/> reference.
1702 /// </param>
1703 /// <param name="value">
1704 /// The object used as the value of the element to add or replace. <see langword="null"/> is allowed.
1705 /// </param>
1706 /// <param name="size">
1707 /// The element's size. Normally bytes, but can be any suitable unit of measure.
1708 /// </param>
1709 /// <returns>
1710 /// <see langword="true"/>if element has been added successfully to the <see cref="ICnmCache{TKey,TValue}"/>;
1711 /// otherwise <see langword="false"/>.
1712 /// </returns>
1713 /// <exception cref="ArgumentNullException">
1714 /// <paramref name="key"/>is <see langword="null"/>.
1715 /// </exception>
1716 /// <exception cref="ArgumentOutOfRangeException">
1717 /// The element's <paramref name="size"/> is less than 0.
1718 /// </exception>
1719 /// <remarks>
1720 /// <para>
1721 /// If element's <paramref name="size"/> is larger than <see cref="ICnmCache{TKey,TValue}.MaxElementSize"/>, then element is
1722 /// not added to the <see cref="ICnmCache{TKey,TValue}"/>, however - possible older element is
1723 /// removed from the <see cref="ICnmCache{TKey,TValue}"/>.
1724 /// </para>
1725 /// <para>
1726 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements,
1727 /// <see cref="ICnmCache{TKey,TValue}"/>will remove less recently used elements until it can fit an new element.
1728 /// </para>
1729 /// <para>
1730 /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count,
1731 /// <see cref="ICnmCache{TKey,TValue}"/>will remove less recently used elements until it can fit an new element.
1732 /// </para>
1733 /// </remarks>
1734 /// <seealso cref="ICnmCache{TKey,TValue}.IsSizeLimited"/>
1735 /// <seealso cref="ICnmCache{TKey,TValue}.IsCountLimited"/>
1736 /// <seealso cref="ICnmCache{TKey,TValue}.Remove"/>
1737 /// <seealso cref="ICnmCache{TKey,TValue}.RemoveRange"/>
1738 /// <seealso cref="ICnmCache{TKey,TValue}.TryGetValue"/>
1739 /// <seealso cref="ICnmCache{TKey,TValue}.Clear"/>
1740 /// <seealso cref="ICnmCache{TKey,TValue}.PurgeExpired"/>
1741 public bool Set( TKey key, TValue value, long size )
1742 {
1743 if( key == null )
1744 throw new ArgumentNullException( "key" );
1745
1746 if( size < 0 )
1747 throw new ArgumentOutOfRangeException( "size", size, "Value's size can't be less than 0." );
1748
1749 if( size > MaxElementSize )
1750 {
1751 // Entry size is too big to fit cache - ignore it
1752 Remove( key );
1753 return false;
1754 }
1755
1756 if( size == 0 )
1757 size = 1;
1758
1759 var bucketIndex = GetBucketIndex( key );
1760 m_oldGeneration.Remove( bucketIndex, key );
1761 AddToNewGeneration( bucketIndex, key, value, size );
1762 CheckExpired();
1763
1764 return true;
1765 }
1766
1767 /// <summary>
1768 /// Gets the <paramref name="value"/> associated with the specified <paramref name="key"/>.
1769 /// </summary>
1770 /// <returns>
1771 /// <see langword="true"/>if the <see cref="ICnmCache{TKey,TValue}"/> contains an element with
1772 /// the specified key; otherwise, <see langword="false"/>.
1773 /// </returns>
1774 /// <param name="key">
1775 /// The key whose <paramref name="value"/> to get.
1776 /// </param>
1777 /// <param name="value">
1778 /// When this method returns, the value associated with the specified <paramref name="key"/>,
1779 /// if the <paramref name="key"/> is found; otherwise, the
1780 /// default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.
1781 /// </param>
1782 /// <exception cref="ArgumentNullException">
1783 /// <paramref name="key"/>is <see langword="null"/>.
1784 /// </exception>
1785 /// <seealso cref="ICnmCache{TKey,TValue}.Set"/>
1786 /// <seealso cref="ICnmCache{TKey,TValue}.Remove"/>
1787 /// <seealso cref="ICnmCache{TKey,TValue}.RemoveRange"/>
1788 /// <seealso cref="ICnmCache{TKey,TValue}.Clear"/>
1789 /// <seealso cref="ICnmCache{TKey,TValue}.PurgeExpired"/>
1790 public bool TryGetValue( TKey key, out TValue value )
1791 {
1792 if( key == null )
1793 throw new ArgumentNullException( "key" );
1794
1795 var bucketIndex = GetBucketIndex( key );
1796 long size;
1797 if( m_newGeneration.TryGetValue( bucketIndex, key, out value, out size ) )
1798 {
1799 CheckExpired();
1800 return true;
1801 }
1802
1803 if( m_oldGeneration.TryGetValue( bucketIndex, key, out value, out size ) )
1804 {
1805 // Move element to new generation
1806 AddToNewGeneration( bucketIndex, key, value, size );
1807 CheckExpired();
1808 return true;
1809 }
1810
1811 CheckExpired();
1812 return false;
1813 }
1814
1815 /// <summary>
1816 /// Returns an enumerator that iterates through a collection.
1817 /// </summary>
1818 /// <returns>
1819 /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
1820 /// </returns>
1821 /// <filterpriority>2</filterpriority>
1822 IEnumerator IEnumerable.GetEnumerator()
1823 {
1824 return GetEnumerator();
1825 }
1826
1827 #endregion
1828 }
1829}