• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

bitfaster / BitFaster.Caching / 9058042176

13 May 2024 06:06AM UTC coverage: 98.62% (-0.2%) from 98.865%
9058042176

push

github

web-flow
Extend test wait (#585)

* retru

* tests

* retry

---------

1050 of 1077 branches covered (97.49%)

Branch coverage included in aggregate %.

4597 of 4649 relevant lines covered (98.88%)

48939987.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.92
/BitFaster.Caching/Lru/ConcurrentLruCore.cs
1
using System;
2
using System.Collections;
3
using System.Collections.Concurrent;
4
using System.Collections.Generic;
5
using System.Diagnostics;
6
using System.Diagnostics.CodeAnalysis;
7
using System.Linq;
8
using System.Runtime.CompilerServices;
9
using System.Threading;
10
using System.Threading.Tasks;
11

12
namespace BitFaster.Caching.Lru
13
{
14
    /// <summary>
15
    /// A pseudo LRU based on the TU-Q eviction policy. The LRU list is composed of 3 segments: hot, warm and cold. 
16
    /// Cost of maintaining segments is amortized across requests. Items are only cycled when capacity is exceeded. 
17
    /// Pure read does not cycle items if all segments are within capacity constraints. There are no global locks. 
18
    /// On cache miss, a new item is added. Tail items in each segment are dequeued, examined, and are either enqueued 
19
    /// or discarded.
20
    /// The TU-Q scheme of hot, warm and cold is similar to that used in MemCached (https://memcached.org/blog/modern-lru/)
21
    /// and OpenBSD (https://flak.tedunangst.com/post/2Q-buffer-cache-algorithm), but does not use a background thread
22
    /// to maintain the internal queues.
23
    /// </summary>
24
    /// <remarks>
25
    /// Each segment has a capacity. When segment capacity is exceeded, items are moved as follows:
26
    /// <list type="number">
27
    ///   <item><description>New items are added to hot, WasAccessed = false.</description></item>
28
    ///   <item><description>When items are accessed, update WasAccessed = true.</description></item>
29
    ///   <item><description>When items are moved WasAccessed is set to false.</description></item>
30
    ///   <item><description>When hot is full, hot tail is moved to either Warm or Cold depending on WasAccessed.</description></item>
31
    ///   <item><description>When warm is full, warm tail is moved to warm head or cold depending on WasAccessed.</description></item>
32
    ///   <item><description>When cold is full, cold tail is moved to warm head or removed from dictionary on depending on WasAccessed.</description></item>
33
    ///</list>
34
    /// </remarks>
35
    public class ConcurrentLruCore<K, V, I, P, T> : ICacheExt<K, V>, IAsyncCacheExt<K, V>, IEnumerable<KeyValuePair<K, V>>
36
        where K : notnull
37
        where I : LruItem<K, V>
38
        where P : struct, IItemPolicy<K, V, I>
39
        where T : struct, ITelemetryPolicy<K, V>
40
    {
41
        private readonly ConcurrentDictionary<K, I> dictionary;
42

43
        private readonly ConcurrentQueue<I> hotQueue;
44
        private readonly ConcurrentQueue<I> warmQueue;
45
        private readonly ConcurrentQueue<I> coldQueue;
46

47
        // maintain count outside ConcurrentQueue, since ConcurrentQueue.Count holds a global lock
48
        private PaddedQueueCount counter;
49

50
        private readonly ICapacityPartition capacity;
51

52
        private readonly P itemPolicy;
53
        private bool isWarm = false;
1,808✔
54

55
        /// <summary>
56
        /// The telemetry policy.
57
        /// </summary>
58
        /// <remarks>
59
        /// Since T is a struct, making it readonly will force the runtime to make defensive copies
60
        /// if mutate methods are called. Therefore, field must be mutable to maintain count.
61
        /// </remarks>
62
        protected T telemetryPolicy;
63

64
        /// <summary>
65
        /// Initializes a new instance of the ConcurrentLruCore class with the specified concurrencyLevel, capacity, equality comparer, item policy and telemetry policy.
66
        /// </summary>
67
        /// <param name="concurrencyLevel">The concurrency level.</param>
68
        /// <param name="capacity">The capacity.</param>
69
        /// <param name="comparer">The equality comparer.</param>
70
        /// <param name="itemPolicy">The item policy.</param>
71
        /// <param name="telemetryPolicy">The telemetry policy.</param>
72
        /// <exception cref="ArgumentNullException"></exception>
73
        public ConcurrentLruCore(
1,808✔
74
            int concurrencyLevel,
1,808✔
75
            ICapacityPartition capacity,
1,808✔
76
            IEqualityComparer<K> comparer,
1,808✔
77
            P itemPolicy,
1,808✔
78
            T telemetryPolicy)
1,808✔
79
        {
1,808✔
80
            if (capacity == null)
1,808✔
81
                Throw.ArgNull(ExceptionArgument.capacity);
4✔
82

83
            if (comparer == null)
1,804✔
84
                Throw.ArgNull(ExceptionArgument.comparer);
4✔
85

86
            capacity.Validate();
1,800✔
87
            this.capacity = capacity;
1,796✔
88

89
            this.hotQueue = new ConcurrentQueue<I>();
1,796✔
90
            this.warmQueue = new ConcurrentQueue<I>();
1,796✔
91
            this.coldQueue = new ConcurrentQueue<I>();
1,796✔
92

93
            int dictionaryCapacity = ConcurrentDictionarySize.Estimate(this.Capacity);
1,796✔
94

95
            this.dictionary = new ConcurrentDictionary<K, I>(concurrencyLevel, dictionaryCapacity, comparer);
1,796✔
96
            this.itemPolicy = itemPolicy;
1,788✔
97
            this.telemetryPolicy = telemetryPolicy;
1,788✔
98
            this.telemetryPolicy.SetEventSource(this);
1,788✔
99
        }
1,788✔
100

101
        // No lock count: https://arbel.net/2013/02/03/best-practices-for-using-concurrentdictionary/
102
        ///<inheritdoc/>
103
        public int Count => this.dictionary.Where(i => !itemPolicy.ShouldDiscard(i.Value)).Count();
13,966,599✔
104

105
        ///<inheritdoc/>
106
        public int Capacity => this.capacity.Hot + this.capacity.Warm + this.capacity.Cold;
1,600,002,640✔
107

108
        ///<inheritdoc/>
109
        public Optional<ICacheMetrics> Metrics => CreateMetrics(this);
108✔
110

111
        ///<inheritdoc/>
112
        public Optional<ICacheEvents<K, V>> Events => CreateEvents(this);
1,056✔
113

114
        ///<inheritdoc/>
115
        public CachePolicy Policy => CreatePolicy(this);
176✔
116

117
        /// <summary>
118
        /// Gets the number of hot items.
119
        /// </summary>
120
        public int HotCount => Volatile.Read(ref this.counter.hot);
1,268,772✔
121

122
        /// <summary>
123
        /// Gets the number of warm items.
124
        /// </summary>
125
        public int WarmCount => Volatile.Read(ref this.counter.warm);
1,268,764✔
126

127
        /// <summary>
128
        /// Gets the number of cold items.
129
        /// </summary>
130
        public int ColdCount => Volatile.Read(ref this.counter.cold);
1,268,768✔
131

132
        /// <summary>
133
        /// Gets a collection containing the keys in the cache.
134
        /// </summary>
135
        public ICollection<K> Keys => this.dictionary.Keys;
760✔
136

137
        /// <summary>Returns an enumerator that iterates through the cache.</summary>
138
        /// <returns>An enumerator for the cache.</returns>
139
        /// <remarks>
140
        /// The enumerator returned from the cache is safe to use concurrently with
141
        /// reads and writes, however it does not represent a moment-in-time snapshot.  
142
        /// The contents exposed through the enumerator may contain modifications
143
        /// made after <see cref="GetEnumerator"/> was called.
144
        /// </remarks>
145
        public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
146
        {
248✔
147
            foreach (var kvp in this.dictionary)
1,260✔
148
            {
260✔
149
                if (!itemPolicy.ShouldDiscard(kvp.Value))
260✔
150
                { 
260✔
151
                    yield return new KeyValuePair<K, V>(kvp.Key, kvp.Value.Value); 
260✔
152
                }
256✔
153
            }
256✔
154
        }
244✔
155

156
        ///<inheritdoc/>
157
        public bool TryGet(K key, [MaybeNullWhen(false)] out V value)
158
        {
1,777,034,713✔
159
            if (dictionary.TryGetValue(key, out var item))
1,777,034,713✔
160
            {
1,613,177,516✔
161
                return GetOrDiscard(item, out value);
1,613,177,516✔
162
            }
163

164
            value = default;
163,857,197✔
165
            this.telemetryPolicy.IncrementMiss();
163,857,197✔
166
            return false;
163,857,197✔
167
        }
1,777,034,713✔
168

169
        // AggressiveInlining forces the JIT to inline policy.ShouldDiscard(). For LRU policy 
170
        // the first branch is completely eliminated due to JIT time constant propogation.
171
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
172
        private bool GetOrDiscard(I item, [MaybeNullWhen(false)] out V value)
173
        {
1,613,177,516✔
174
            if (this.itemPolicy.ShouldDiscard(item))
1,613,177,516✔
175
            {
2,829,344✔
176
                this.Move(item, ItemDestination.Remove, ItemRemovedReason.Evicted);
2,829,344✔
177
                this.telemetryPolicy.IncrementMiss();
2,829,344✔
178
                value = default;
2,829,344✔
179
                return false;
2,829,344✔
180
            }
181

182
            value = item.Value;
1,610,348,172✔
183
            this.itemPolicy.Touch(item);
1,610,348,172✔
184
            this.telemetryPolicy.IncrementHit();
1,610,348,172✔
185
            return true;
1,610,348,172✔
186
        }
1,613,177,516✔
187

188
        private bool TryAdd(K key, V value)
189
        {
166,686,453✔
190
            var newItem = this.itemPolicy.CreateItem(key, value);
166,686,453✔
191

192
            if (this.dictionary.TryAdd(key, newItem))
166,686,453✔
193
            {
158,676,711✔
194
                this.hotQueue.Enqueue(newItem);
158,676,711✔
195
                Cycle(Interlocked.Increment(ref counter.hot));
158,676,711✔
196
                return true;
158,676,711✔
197
            }
198

199
            Disposer<V>.Dispose(newItem.Value);
8,009,742✔
200
            return false;
8,009,742✔
201
        }
166,686,453✔
202

203
        ///<inheritdoc/>
204
        public V GetOrAdd(K key, Func<K, V> valueFactory)
205
        {
1,721,023,587✔
206
            while (true)
1,727,460,118✔
207
            {
1,727,460,118✔
208
                if (this.TryGet(key, out var value))
1,727,460,118✔
209
                {
1,606,233,724✔
210
                    return value;
1,606,233,724✔
211
                }
212

213
                // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
214
                value = valueFactory(key);
121,226,394✔
215

216
                if (TryAdd(key, value))
121,226,394✔
217
                {
114,789,863✔
218
                    return value;
114,789,863✔
219
                }
220
            }
6,436,531✔
221
        }
1,721,023,587✔
222

223
        /// <summary>
224
        /// Adds a key/value pair to the cache if the key does not already exist. Returns the new value, or the 
225
        /// existing value if the key already exists.
226
        /// </summary>
227
        /// <typeparam name="TArg">The type of an argument to pass into valueFactory.</typeparam>
228
        /// <param name="key">The key of the element to add.</param>
229
        /// <param name="valueFactory">The factory function used to generate a value for the key.</param>
230
        /// <param name="factoryArgument">An argument value to pass into valueFactory.</param>
231
        /// <returns>The value for the key. This will be either the existing value for the key if the key is already 
232
        /// in the cache, or the new value if the key was not in the cache.</returns>
233
        public V GetOrAdd<TArg>(K key, Func<K, TArg, V> valueFactory, TArg factoryArgument)
234
        {
16,000,012✔
235
            while (true)
16,503,887✔
236
            {
16,503,887✔
237
                if (this.TryGet(key, out var value))
16,503,887✔
238
                {
1,434,385✔
239
                    return value;
1,434,385✔
240
                }
241

242
                // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
243
                value = valueFactory(key, factoryArgument);
15,069,502✔
244

245
                if (TryAdd(key, value))
15,069,502✔
246
                {
14,565,627✔
247
                    return value;
14,565,627✔
248
                }
249
            }
503,875✔
250
        }
16,000,012✔
251

252
        ///<inheritdoc/>
253
        public async ValueTask<V> GetOrAddAsync(K key, Func<K, Task<V>> valueFactory)
254
        {
16,000,304✔
255
            while (true)
16,485,180✔
256
            {
16,485,180✔
257
                if (this.TryGet(key, out var value))
16,485,180✔
258
                {
1,221,276✔
259
                    return value;
1,221,276✔
260
                }
261

262
                // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
263
                // This is identical logic in ConcurrentDictionary.GetOrAdd method.
264
                value = await valueFactory(key).ConfigureAwait(false);
15,263,904✔
265

266
                if (TryAdd(key, value))
15,263,892✔
267
                {
14,779,016✔
268
                    return value;
14,779,016✔
269
                }
270
            }
484,876✔
271
        }
16,000,292✔
272

273
        /// <summary>
274
        /// Adds a key/value pair to the cache if the key does not already exist. Returns the new value, or the 
275
        /// existing value if the key already exists.
276
        /// </summary>
277
        /// <typeparam name="TArg">The type of an argument to pass into valueFactory.</typeparam>
278
        /// <param name="key">The key of the element to add.</param>
279
        /// <param name="valueFactory">The factory function used to asynchronously generate a value for the key.</param>
280
        /// <param name="factoryArgument">An argument value to pass into valueFactory.</param>
281
        /// <returns>A task that represents the asynchronous GetOrAdd operation.</returns>
282
        public async ValueTask<V> GetOrAddAsync<TArg>(K key, Func<K, TArg, Task<V>> valueFactory, TArg factoryArgument)
283
        {
16,000,276✔
284
            while (true)
16,584,736✔
285
            {
16,584,736✔
286
                if (this.TryGet(key, out var value))
16,584,736✔
287
                {
1,458,071✔
288
                    return value;
1,458,071✔
289
                }
290

291
                // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
292
                value = await valueFactory(key, factoryArgument).ConfigureAwait(false);
15,126,665✔
293

294
                if (TryAdd(key, value))
15,126,665✔
295
                {
14,542,205✔
296
                    return value;
14,542,205✔
297
                }
298
            }
584,460✔
299
        }
16,000,276✔
300

301
        /// <summary>
302
        /// Attempts to remove the specified key value pair.
303
        /// </summary>
304
        /// <param name="item">The item to remove.</param>
305
        /// <returns>true if the item was removed successfully; otherwise, false.</returns>
306
        public bool TryRemove(KeyValuePair<K, V> item)
307
        {
16,000,028✔
308
            if (this.dictionary.TryGetValue(item.Key, out var existing))
16,000,028✔
309
            {
49,207✔
310
                if (EqualityComparer<V>.Default.Equals(existing.Value, item.Value))
49,207✔
311
                {
49,191✔
312
                    var kvp = new KeyValuePair<K, I>(item.Key, existing);
49,191✔
313
#if NET6_0_OR_GREATER
314
                    if (this.dictionary.TryRemove(kvp))
34,957✔
315
#else
316
                    // https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/
317
                    if (((ICollection<KeyValuePair<K, I>>)this.dictionary).Remove(kvp))
14,234✔
318
#endif
319
                    {
39,893✔
320
                        OnRemove(item.Key, kvp.Value, ItemRemovedReason.Removed);
39,893✔
321
                        return true;
39,893✔
322
                    }
323
                }
9,298✔
324

325
                // it existed, but we couldn't remove - this means value was replaced afer the TryGetValue (a race)
326
            }
9,314✔
327

328
            return false;
15,960,135✔
329
        }
16,000,028✔
330

331
        /// <summary>
332
        /// Attempts to remove and return the value that has the specified key.
333
        /// </summary>
334
        /// <param name="key">The key of the element to remove.</param>
335
        /// <param name="value">When this method returns, contains the object removed, or the default value of the value type if key does not exist.</param>
336
        /// <returns>true if the object was removed successfully; otherwise, false.</returns>
337
        public bool TryRemove(K key, [MaybeNullWhen(false)] out V value)
338
        {
16,000,196✔
339
            if (this.dictionary.TryRemove(key, out var item))
16,000,196✔
340
            {
45,491✔
341
                OnRemove(key, item, ItemRemovedReason.Removed);
45,491✔
342
                value = item.Value;
45,491✔
343
                return true;
45,491✔
344
            }
345

346
            value = default;
15,954,705✔
347
            return false;
15,954,705✔
348
        }
16,000,196✔
349

350
        ///<inheritdoc/>
351
        public bool TryRemove(K key)
352
        {
16,000,132✔
353
            return TryRemove(key, out _);
16,000,132✔
354
        }
16,000,132✔
355

356
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
357
        private void OnRemove(K key, I item, ItemRemovedReason reason)
358
        {
172,615,733✔
359
            // Mark as not accessed, it will later be cycled out of the queues because it can never be fetched 
360
            // from the dictionary. Note: Hot/Warm/Cold count will reflect the removed item until it is cycled 
361
            // from the queue.
362
            item.WasAccessed = false;
172,615,733✔
363
            item.WasRemoved = true;
172,615,733✔
364

365
            this.telemetryPolicy.OnItemRemoved(key, item.Value, reason);
172,615,733✔
366

367
            // serialize dispose (common case dispose not thread safe)
368
            lock (item)
172,615,733✔
369
            {
172,615,733✔
370
                Disposer<V>.Dispose(item.Value);
172,615,733✔
371
            }
172,615,733✔
372
        }
172,615,733✔
373

374
        ///<inheritdoc/>
375
        ///<remarks>Note: Calling this method does not affect LRU order.</remarks>
376
        public bool TryUpdate(K key, V value)
377
        {
32,150,331✔
378
            if (this.dictionary.TryGetValue(key, out var existing))
32,150,331✔
379
            {
2,581,977✔
380
                lock (existing)
2,581,977✔
381
                {
2,581,977✔
382
                    if (!existing.WasRemoved)
2,581,977✔
383
                    {
2,581,938✔
384
                        V oldValue = existing.Value;
2,581,938✔
385
                        existing.Value = value;
2,581,938✔
386
                        this.itemPolicy.Update(existing);
2,581,938✔
387
// backcompat: remove conditional compile
388
#if NETCOREAPP3_0_OR_GREATER
389
                        this.telemetryPolicy.OnItemUpdated(existing.Key, oldValue, existing.Value);
2,581,938✔
390
#endif
391
                        Disposer<V>.Dispose(oldValue);
2,581,938✔
392

393
                        return true;
2,581,938✔
394
                    }
395
                }
39✔
396
            }
39✔
397

398
            return false;
29,568,393✔
399
        }
32,150,331✔
400

401
        ///<inheritdoc/>
402
        ///<remarks>Note: Updates to existing items do not affect LRU order. Added items are at the top of the LRU.</remarks>
403
        public void AddOrUpdate(K key, V value)
404
        {
16,002,336✔
405
            while (true)
16,150,243✔
406
            {
16,150,243✔
407
                // first, try to update
408
                if (this.TryUpdate(key, value))
16,150,243✔
409
                {
2,036,555✔
410
                    return;
2,036,555✔
411
                }
412

413
                // then try add
414
                var newItem = this.itemPolicy.CreateItem(key, value);
14,113,688✔
415

416
                if (this.dictionary.TryAdd(key, newItem))
14,113,688✔
417
                {
13,965,781✔
418
                    this.hotQueue.Enqueue(newItem);
13,965,781✔
419
                    Cycle(Interlocked.Increment(ref counter.hot));
13,965,781✔
420
                    return;
13,965,781✔
421
                }
422

423
                // if both update and add failed there was a race, try again
424
            }
147,907✔
425
        }
16,002,336✔
426

427
        ///<inheritdoc/>
428
        public void Clear()
429
        {
1,250,128✔
430
            // don't overlap Clear/Trim/TrimExpired
431
            lock (this.dictionary)
1,250,128✔
432
            {
1,250,128✔
433
                // evaluate queue count, remove everything including items removed from the dictionary but
434
                // not the queues. This also avoids the expensive o(n) no lock count, or locking the dictionary.
435
                int queueCount = this.HotCount + this.WarmCount + this.ColdCount;
1,250,128✔
436
                this.TrimLiveItems(itemsRemoved: 0, queueCount, ItemRemovedReason.Cleared);
1,250,128✔
437
            }
1,250,128✔
438
        }
1,250,128✔
439

440
        /// <summary>
441
        /// Trim the specified number of items from the cache. Removes all discardable items per IItemPolicy.ShouldDiscard(), then 
442
        /// itemCount-discarded items in LRU order, if any.
443
        /// </summary>
444
        /// <param name="itemCount">The number of items to remove.</param>
445
        /// <returns>The number of items removed from the cache.</returns>
446
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="itemCount"/> is less than 0./</exception>
447
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="itemCount"/> is greater than capacity./</exception>
448
        /// <remarks>
449
        /// Note: Trim affects LRU order. Calling Trim resets the internal accessed status of items.
450
        /// </remarks>
451
        public void Trim(int itemCount)
452
        {
228✔
453
            int capacity = this.Capacity;
228✔
454

455
            if (itemCount < 1 || itemCount > capacity)
228✔
456
                Throw.ArgOutOfRange(nameof(itemCount), "itemCount must be greater than or equal to one, and less than the capacity of the cache.");
8✔
457

458
            // clamp itemCount to number of items actually in the cache
459
            itemCount = Math.Min(itemCount, this.HotCount + this.WarmCount + this.ColdCount);
220✔
460

461
            // don't overlap Clear/Trim/TrimExpired
462
            lock (this.dictionary)
220✔
463
            {
220✔
464
                // first scan each queue for discardable items and remove them immediately. Note this can remove > itemCount items.
465
                int itemsRemoved = this.itemPolicy.CanDiscard() ? TrimAllDiscardedItems() : 0;
220!
466

467
                TrimLiveItems(itemsRemoved, itemCount, ItemRemovedReason.Trimmed);
220✔
468
            }
220✔
469
        }
220✔
470

471
        private void TrimExpired()
472
        {
4✔
473
            if (this.itemPolicy.CanDiscard())
4✔
474
            {
4✔
475
                this.TrimAllDiscardedItems();
4✔
476
            }
4✔
477
        }
4✔
478

479
        /// <summary>
480
        /// Trim discarded items from all queues.
481
        /// </summary>
482
        /// <returns>The number of items removed.</returns>
483
        // backcompat: make internal
484
        protected int TrimAllDiscardedItems()
485
        {
4✔
486
            // don't overlap Clear/Trim/TrimExpired
487
            lock (this.dictionary)
4✔
488
            {
4✔
489
                int RemoveDiscardableItems(ConcurrentQueue<I> q, ref int queueCounter)
490
                {
12✔
491
                    int itemsRemoved = 0;
12✔
492
                    int localCount = queueCounter;
12✔
493

494
                    for (int i = 0; i < localCount; i++)
48✔
495
                    {
12✔
496
                        if (q.TryDequeue(out var item))
12✔
497
                        {
12✔
498
                            if (this.itemPolicy.ShouldDiscard(item))
12!
499
                            {
12✔
500
                                Interlocked.Decrement(ref queueCounter);
12✔
501
                                this.Move(item, ItemDestination.Remove, ItemRemovedReason.Trimmed);
12✔
502
                                itemsRemoved++;
12✔
503
                            }
12✔
504
                            else
505
                            {
×
506
                                q.Enqueue(item);
×
507
                            }
×
508
                        }
12✔
509
                    }
12✔
510

511
                    return itemsRemoved;
12✔
512
                }
12✔
513

514
                int coldRem = RemoveDiscardableItems(coldQueue, ref this.counter.cold);
4✔
515
                int warmRem = RemoveDiscardableItems(warmQueue, ref this.counter.warm);
4✔
516
                int hotRem = RemoveDiscardableItems(hotQueue, ref this.counter.hot);
4✔
517

518
                if (warmRem > 0)
4✔
519
                {
4✔
520
                    Volatile.Write(ref this.isWarm, false);
4✔
521
                }
4✔
522

523
                return coldRem + warmRem + hotRem;
4✔
524
            }
525
        }
4✔
526

527
        private void TrimLiveItems(int itemsRemoved, int itemCount, ItemRemovedReason reason)
528
        {
1,250,348✔
529
            // When items are touched, they are moved to warm by cycling. Therefore, to guarantee 
530
            // that we can remove itemCount items, we must cycle (2 * capacity.Warm) + capacity.Hot times.
531
            // If clear is called during trimming, it would be possible to get stuck in an infinite
532
            // loop here. The warm + hot limit also guards against this case.
533
            int trimWarmAttempts = 0;
1,250,348✔
534
            int maxWarmHotAttempts = (this.capacity.Warm * 2) + this.capacity.Hot;
1,250,348✔
535

536
            while (itemsRemoved < itemCount && trimWarmAttempts < maxWarmHotAttempts)
10,734,990✔
537
            {
9,484,642✔
538
                if (Volatile.Read(ref this.counter.cold) > 0)
9,484,642✔
539
                {
8,864,480✔
540
                    if (TryRemoveCold(reason) == (ItemDestination.Remove, 0))
8,864,480✔
541
                    {
8,863,343✔
542
                        itemsRemoved++;
8,863,343✔
543
                        trimWarmAttempts = 0;
8,863,343✔
544
                    }
8,863,343✔
545

546
                    TrimWarmOrHot(reason);
8,864,480✔
547
                }
8,864,480✔
548
                else
549
                {
620,162✔
550
                    TrimWarmOrHot(reason);
620,162✔
551
                    trimWarmAttempts++;
620,162✔
552
                }
620,162✔
553
            }
9,484,642✔
554

555
            if (Volatile.Read(ref this.counter.warm) < this.capacity.Warm)
1,250,348✔
556
            {
1,250,265✔
557
                Volatile.Write(ref this.isWarm, false);
1,250,265✔
558
            }
1,250,265✔
559
        }
1,250,348✔
560

561
        private void TrimWarmOrHot(ItemRemovedReason reason)
562
        {
9,484,642✔
563
            if (Volatile.Read(ref this.counter.warm) > 0)
9,484,642✔
564
            {
3,474,182✔
565
                CycleWarmUnchecked(reason);
3,474,182✔
566
            }
3,474,182✔
567
            else if (Volatile.Read(ref this.counter.hot) > 0)
6,010,460✔
568
            {
5,153,613✔
569
                CycleHotUnchecked(reason);
5,153,613✔
570
            }
5,153,613✔
571
        }
9,484,642✔
572

573
        private void Cycle(int hotCount)
574
        {
172,642,492✔
575
            if (isWarm)
172,642,492✔
576
            {
166,873,837✔
577
                (var dest, var count) = CycleHot(hotCount);
166,873,837✔
578

579
                int cycles = 0;
166,873,837✔
580
                while (cycles++ < 3 && dest != ItemDestination.Remove)
358,234,725✔
581
                {
191,360,888✔
582
                    if (dest == ItemDestination.Warm)
191,360,888✔
583
                    {
30,523,463✔
584
                        (dest, count) = CycleWarm(count);
30,523,463✔
585
                    }
30,523,463✔
586
                    else if (dest == ItemDestination.Cold)
160,837,425✔
587
                    {
160,837,425✔
588
                        (dest, count) = CycleCold(count);
160,837,425✔
589
                    }
160,837,425✔
590
                }
191,360,888✔
591

592
                // If nothing was removed yet, constrain the size of warm and cold by discarding the coldest item.
593
                if (dest != ItemDestination.Remove)
166,873,837✔
594
                {
3,644,842✔
595
                    if (dest == ItemDestination.Warm && count > this.capacity.Warm)
3,644,842✔
596
                    {
2,338,897✔
597
                        count = LastWarmToCold();
2,338,897✔
598
                    }
2,338,897✔
599

600
                    ConstrainCold(count, ItemRemovedReason.Evicted);
3,644,842✔
601
                }
3,644,842✔
602
            }
166,873,837✔
603
            else
604
            {
5,768,655✔
605
                // fill up the warm queue with new items until warm is full.
606
                // else during warmup the cache will only use the hot + cold queues until any item is requested twice.
607
                CycleDuringWarmup(hotCount);
5,768,655✔
608
            }
5,768,655✔
609
        }
172,642,492✔
610

611
        [MethodImpl(MethodImplOptions.NoInlining)]
612
        private void CycleDuringWarmup(int hotCount)
613
        {
5,768,655✔
614
            // do nothing until hot is full
615
            if (hotCount > this.capacity.Hot)
5,768,655✔
616
            {
3,360,503✔
617
                Interlocked.Decrement(ref this.counter.hot);
3,360,503✔
618

619
                if (this.hotQueue.TryDequeue(out var item))
3,360,503✔
620
                {
3,360,500✔
621
                    int count = this.Move(item, ItemDestination.Warm, ItemRemovedReason.Evicted);
3,360,500✔
622

623
                    // if warm is now full, overflow to cold and mark as warm
624
                    if (count > this.capacity.Warm)
3,360,500✔
625
                    {
953,823✔
626
                        Volatile.Write(ref this.isWarm, true);
953,823✔
627
                        count = LastWarmToCold();
953,823✔
628
                        ConstrainCold(count, ItemRemovedReason.Evicted);
953,823✔
629
                    }
953,823✔
630
                }
3,360,500✔
631
                else
632
                {
3✔
633
                    Interlocked.Increment(ref this.counter.hot);
3✔
634
                }
3✔
635
            }
3,360,503✔
636
        }
5,768,655✔
637

638
        private (ItemDestination, int) CycleHot(int hotCount)
639
        {
166,873,837✔
640
            if (hotCount > this.capacity.Hot)
166,873,837✔
641
            {
164,121,830✔
642
                return CycleHotUnchecked(ItemRemovedReason.Evicted);
164,121,830✔
643
            }
644

645
            return (ItemDestination.Remove, 0);
2,752,007✔
646
        }
166,873,837✔
647

648
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
649
        private (ItemDestination, int) CycleHotUnchecked(ItemRemovedReason removedReason)
650
        {
169,275,443✔
651
            Interlocked.Decrement(ref this.counter.hot);
169,275,443✔
652

653
            if (this.hotQueue.TryDequeue(out var item))
169,275,443✔
654
            {
169,275,428✔
655
                var where = this.itemPolicy.RouteHot(item);
169,275,428✔
656
                return (where, this.Move(item, where, removedReason));
169,275,428✔
657
            }
658
            else
659
            {
15✔
660
                Interlocked.Increment(ref this.counter.hot);
15✔
661
                return (ItemDestination.Remove, 0);
15✔
662
            }
663
        }
169,275,443✔
664

665
        private (ItemDestination, int) CycleWarm(int count)
666
        {
30,523,463✔
667
            if (count > this.capacity.Warm)
30,523,463✔
668
            {
29,464,854✔
669
                return CycleWarmUnchecked(ItemRemovedReason.Evicted);
29,464,854✔
670
            }
671

672
            return (ItemDestination.Remove, 0);
1,058,609✔
673
        }
30,523,463✔
674

675
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
676
        private (ItemDestination, int) CycleWarmUnchecked(ItemRemovedReason removedReason)
677
        {
32,939,036✔
678
            int wc = Interlocked.Decrement(ref this.counter.warm);
32,939,036✔
679

680
            if (this.warmQueue.TryDequeue(out var item))
32,939,036✔
681
            {
32,939,031✔
682
                var where = this.itemPolicy.RouteWarm(item);
32,939,031✔
683

684
                // When the warm queue is full, we allow an overflow of 1 item before redirecting warm items to cold.
685
                // This only happens when hit rate is high, in which case we can consider all items relatively equal in
686
                // terms of which was least recently used.
687
                if (where == ItemDestination.Warm && wc <= this.capacity.Warm)
32,939,031✔
688
                {
6,976,797✔
689
                    return (ItemDestination.Warm, this.Move(item, where, removedReason));
6,976,797✔
690
                }
691
                else
692
                {
25,962,234✔
693
                    return (ItemDestination.Cold, this.Move(item, ItemDestination.Cold, removedReason));
25,962,234✔
694
                }
695
            }
696
            else
697
            {
5✔
698
                Interlocked.Increment(ref this.counter.warm);
5✔
699
                return (ItemDestination.Remove, 0);
5✔
700
            }
701
        }
32,939,036✔
702

703
        private (ItemDestination, int) CycleCold(int count)
704
        {
160,837,425✔
705
            if (count > this.capacity.Cold)
160,837,425✔
706
            {
160,655,168✔
707
                return TryRemoveCold(ItemRemovedReason.Evicted);
160,655,168✔
708
            }
709

710
            return (ItemDestination.Remove, 0);
182,257✔
711
        }
160,837,425✔
712

713
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
714
        private (ItemDestination, int) TryRemoveCold(ItemRemovedReason removedReason)
715
        {
169,519,648✔
716
            Interlocked.Decrement(ref this.counter.cold);
169,519,648✔
717

718
            if (this.coldQueue.TryDequeue(out var item))
169,519,648✔
719
            {
169,519,028✔
720
                var where = this.itemPolicy.RouteCold(item);
169,519,028✔
721

722
                if (where == ItemDestination.Warm && Volatile.Read(ref this.counter.warm) <= this.capacity.Warm)
169,519,028✔
723
                {
2,277,722✔
724
                    return (ItemDestination.Warm, this.Move(item, where, removedReason));
2,277,722✔
725
                }
726
                else
727
                {
167,241,306✔
728
                    this.Move(item, ItemDestination.Remove, removedReason);
167,241,306✔
729
                    return (ItemDestination.Remove, 0);
167,241,306✔
730
                }
731
            }
732
            else
733
            {
620✔
734
                return (ItemDestination.Cold, Interlocked.Increment(ref this.counter.cold));
620✔
735
            }
736
        }
169,519,648✔
737

738
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
739
        private int LastWarmToCold()
740
        {
3,292,720✔
741
            Interlocked.Decrement(ref this.counter.warm);
3,292,720✔
742

743
            if (this.warmQueue.TryDequeue(out var item))
3,292,720✔
744
            {
3,292,717✔
745
                return this.Move(item, ItemDestination.Cold, ItemRemovedReason.Evicted);
3,292,717✔
746
            }
747
            else
748
            {
3✔
749
                Interlocked.Increment(ref this.counter.warm);
3✔
750
                return 0;
3✔
751
            }
752
        }
3,292,720✔
753

754
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
755
        private void ConstrainCold(int coldCount, ItemRemovedReason removedReason)
756
        {
4,598,665✔
757
            if (coldCount > this.capacity.Cold && this.coldQueue.TryDequeue(out var item))
4,598,665✔
758
            {
4,515,766✔
759
                Interlocked.Decrement(ref this.counter.cold);
4,515,766✔
760
                this.Move(item, ItemDestination.Remove, removedReason);
4,515,766✔
761
            }
4,515,766✔
762
        }
4,598,665✔
763

764
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
765
        private int Move(I item, ItemDestination where, ItemRemovedReason removedReason)
766
        {
385,731,826✔
767
            item.WasAccessed = false;
385,731,826✔
768

769
            switch (where)
385,731,826✔
770
            {
771
                case ItemDestination.Warm:
772
                    this.warmQueue.Enqueue(item);
36,246,596✔
773
                    return Interlocked.Increment(ref this.counter.warm);
36,246,596✔
774
                case ItemDestination.Cold:
775
                    this.coldQueue.Enqueue(item);
174,040,662✔
776
                    return Interlocked.Increment(ref this.counter.cold);
174,040,662✔
777
                case ItemDestination.Remove:
778

779
                    var kvp = new KeyValuePair<K, I>(item.Key, item);
175,444,568✔
780

781
#if NET6_0_OR_GREATER
782
                    if (this.dictionary.TryRemove(kvp))
133,970,926✔
783
#else
784
                    // https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/
785
                    if (((ICollection<KeyValuePair<K, I>>)this.dictionary).Remove(kvp))
41,473,642✔
786
#endif
787
                    {
172,530,349✔
788
                        OnRemove(item.Key, item, removedReason);
172,530,349✔
789
                    }
172,530,349✔
790
                    break;
175,444,568✔
791
            }
792

793
            return 0;
175,444,568✔
794
        }
385,731,826✔
795

796
        /// <summary>Returns an enumerator that iterates through the cache.</summary>
797
        /// <returns>An enumerator for the cache.</returns>
798
        /// <remarks>
799
        /// The enumerator returned from the cache is safe to use concurrently with
800
        /// reads and writes, however it does not represent a moment-in-time snapshot.  
801
        /// The contents exposed through the enumerator may contain modifications
802
        /// made after <see cref="GetEnumerator"/> was called.
803
        /// </remarks>
804
        IEnumerator IEnumerable.GetEnumerator()
805
        {
8✔
806
            return ((ConcurrentLruCore<K, V, I, P, T>)this).GetEnumerator();
8✔
807
        }
8✔
808

809
        private static CachePolicy CreatePolicy(ConcurrentLruCore<K, V, I, P, T> lru)
810
        {
176✔
811
            var p = new Proxy(lru);
176✔
812

813
            if (typeof(P) == typeof(AfterAccessPolicy<K, V>))
176✔
814
            {
32✔
815
                return new CachePolicy(new Optional<IBoundedPolicy>(p), Optional<ITimePolicy>.None(), new Optional<ITimePolicy>(p), Optional<IDiscreteTimePolicy>.None());
32✔
816
            }
817

818
            // IsAssignableFrom is a jit intrinsic https://github.com/dotnet/runtime/issues/4920
819
            if (typeof(IDiscreteItemPolicy<K, V>).IsAssignableFrom(typeof(P)))
144✔
820
            {
44✔
821
                return new CachePolicy(new Optional<IBoundedPolicy>(p), Optional<ITimePolicy>.None(), Optional<ITimePolicy>.None(), new Optional<IDiscreteTimePolicy>(new DiscreteExpiryProxy(lru)));
44✔
822
            }
823

824
            return new CachePolicy(new Optional<IBoundedPolicy>(p), lru.itemPolicy.CanDiscard() ? new Optional<ITimePolicy>(p) : Optional<ITimePolicy>.None());
100✔
825
        }
176✔
826

827
        private static Optional<ICacheMetrics> CreateMetrics(ConcurrentLruCore<K, V, I, P, T> lru)
828
        {
108✔
829
            if (typeof(T) == typeof(NoTelemetryPolicy<K, V>))
108✔
830
            {
20✔
831
                return Optional<ICacheMetrics>.None();
20✔
832
            }
833

834
            return new(new Proxy(lru));
88✔
835
        }
108✔
836

837
        private static Optional<ICacheEvents<K, V>> CreateEvents(ConcurrentLruCore<K, V, I, P, T> lru)
838
        {
1,056✔
839
            if (typeof(T) == typeof(NoTelemetryPolicy<K, V>))
1,056✔
840
            {
52✔
841
                return Optional<ICacheEvents<K, V>>.None();
52✔
842
            }
843

844
            return new(new Proxy(lru));
1,004✔
845
        }
1,056✔
846

847
        // To get JIT optimizations, policies must be structs.
848
        // If the structs are returned directly via properties, they will be copied. Since  
849
        // telemetryPolicy is a mutable struct, copy is bad. One workaround is to store the 
850
        // state within the struct in an object. Since the struct points to the same object
851
        // it becomes immutable. However, this object is then somewhere else on the 
852
        // heap, which slows down the policies with hit counter logic in benchmarks. Likely
853
        // this approach keeps the structs data members in the same CPU cache line as the LRU.
854
        // backcompat: remove conditional compile
855
#if NETCOREAPP3_0_OR_GREATER
856
        [DebuggerDisplay("Hit = {Hits}, Miss = {Misses}, Upd = {Updated}, Evict = {Evicted}")]
857
#else
858
        [DebuggerDisplay("Hit = {Hits}, Miss = {Misses}, Evict = {Evicted}")]
859
#endif
860
        private class Proxy : ICacheMetrics, ICacheEvents<K, V>, IBoundedPolicy, ITimePolicy
861
        {
862
            private readonly ConcurrentLruCore<K, V, I, P, T> lru;
863

864
            public Proxy(ConcurrentLruCore<K, V, I, P, T> lru)
1,268✔
865
            {
1,268✔
866
                this.lru = lru;
1,268✔
867
            }
1,268✔
868

869
            public double HitRatio => lru.telemetryPolicy.HitRatio;
8✔
870

871
            public long Total => lru.telemetryPolicy.Total;
4✔
872

873
            public long Hits => lru.telemetryPolicy.Hits;
24✔
874

875
            public long Misses => lru.telemetryPolicy.Misses;
24✔
876

877
            public long Evicted => lru.telemetryPolicy.Evicted;
8✔
878

879
// backcompat: remove conditional compile
880
#if NETCOREAPP3_0_OR_GREATER
881
            public long Updated => lru.telemetryPolicy.Updated;
8✔
882
#endif
883
            public int Capacity => lru.Capacity;
60✔
884

885
            public TimeSpan TimeToLive => lru.itemPolicy.TimeToLive;
16✔
886

887
            public event EventHandler<ItemRemovedEventArgs<K, V>> ItemRemoved
888
            {
889
                add { this.lru.telemetryPolicy.ItemRemoved += value; }
180✔
890
                remove { this.lru.telemetryPolicy.ItemRemoved -= value; }
24✔
891
            }
892

893
// backcompat: remove conditional compile
894
#if NETCOREAPP3_0_OR_GREATER
895
            public event EventHandler<ItemUpdatedEventArgs<K, V>> ItemUpdated
896
            {
897
                add { this.lru.telemetryPolicy.ItemUpdated += value; }
108✔
898
                remove { this.lru.telemetryPolicy.ItemUpdated -= value; }
12✔
899
            }
900
#endif
901
            public void Trim(int itemCount)
902
            {
24✔
903
                lru.Trim(itemCount);
24✔
904
            }
24✔
905

906
            public void TrimExpired()
907
            {
4✔
908
                lru.TrimExpired();
4✔
909
            }
4✔
910
        }
911

912
        private class DiscreteExpiryProxy : IDiscreteTimePolicy
913
        {
914
            private readonly ConcurrentLruCore<K, V, I, P, T> lru;
915

916
            public DiscreteExpiryProxy(ConcurrentLruCore<K, V, I, P, T> lru)
44✔
917
            {
44✔
918
                this.lru = lru;
44✔
919
            }
44✔
920

921
            public void TrimExpired()
922
            {
×
923
                lru.TrimExpired();
×
924
            }
×
925

926
            public bool TryGetTimeToExpire<TKey>(TKey key, out TimeSpan timeToLive)
927
            {
8✔
928
                if (key is K k && lru.dictionary.TryGetValue(k, out var item))
8!
929
                {
×
930
                    LongTickCountLruItem<K, V>? tickItem = item as LongTickCountLruItem<K, V>;
×
931
                    timeToLive = (new Duration(tickItem!.TickCount) - Duration.SinceEpoch()).ToTimeSpan();
×
932
                    return true;
×
933
                }
934

935
                timeToLive = default;
8✔
936
                return false;
8✔
937
            }
8✔
938
        }
939
    }
940
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc