/// <summary> /// Creates a new instance of ConcurrentCacheMap using the default values /// and a <see cref="CacheMap{TKey,TValue}"/> for the internal data structure. /// </summary> /// /// <param name="timeToLiveSeconds">The time-to-live value (seconds).</param> /// <param name="maxEntries">The maximum number of entries until items gets replaced with LRU.</param> /// <param name="refreshTimeout">If set to true, timeout will be reset in case of PutIfAbsent().</param> public ConcurrentCacheMap(int timeToLiveSeconds, int maxEntries, bool refreshTimeout) { _segments = new CacheMap <TKey, ExpiringObject> [SegmentNr]; int maxEntriesPerSegment = maxEntries / SegmentNr; for (int i = 0; i < SegmentNr; i++) { // set updateOnInsert to true, since it should behave as a regular map _segments[i] = new CacheMap <TKey, ExpiringObject>(maxEntriesPerSegment, true); } _timeToLiveSeconds = timeToLiveSeconds; _refreshTimeout = refreshTimeout; }
/// <summary> /// Fast expiration. Since the ExpiringObject is ordered, the for-loop can break /// eaely if an object is not expired. /// </summary> /// <param name="segment">The segment.</param> private void ExpireSegment(CacheMap <TKey, ExpiringObject> segment) { //.NET-specific: iterate over KeyValuePairs foreach (var kvp in segment.ToList()) // iterate over copy { var expObj = kvp.Value; if (expObj.IsExpired) { segment.Remove(kvp.Key); // remove from original Logger.Debug("Removed in expire segment: {0}.", expObj.Value); _removedCounter.IncrementAndGet(); } else { break; } } }
/// <summary> /// Expires a key in a segment. If a key value pair is expired, it will get removed. /// </summary> /// <param name="segment">The segment.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>True, if expired. False, otherwise.</returns> private bool Expire(CacheMap <TKey, ExpiringObject> segment, TKey key, ExpiringObject value) { if (value.IsExpired) { lock (segment) { var tmp = segment.Get(key); if (tmp != null && tmp.Equals(value)) { segment.Remove(key); Logger.Debug("Removed in expire: {0}.", value.Value); _removedCounter.IncrementAndGet(); } } return(true); } return(false); }