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

bitfaster / BitFaster.Caching / 13893508860

17 Mar 2025 07:05AM UTC coverage: 98.969% (-0.03%) from 99.002%
13893508860

Pull #678

github

web-flow
Merge b5e14340d into db9f9e7b4
Pull Request #678: Bump Microsoft.Extensions.Caching.Memory from 9.0.2 to 9.0.3

1120 of 1146 branches covered (97.73%)

Branch coverage included in aggregate %.

4829 of 4865 relevant lines covered (99.26%)

55178386.91 hits per line

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

97.6
/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;
2,041✔
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(
2,041✔
74
            int concurrencyLevel,
2,041✔
75
            ICapacityPartition capacity,
2,041✔
76
            IEqualityComparer<K> comparer,
2,041✔
77
            P itemPolicy,
2,041✔
78
            T telemetryPolicy)
2,041✔
79
        {
2,041✔
80
            if (capacity == null)
2,041✔
81
                Throw.ArgNull(ExceptionArgument.capacity);
4✔
82

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

86
            capacity.Validate();
2,033✔
87
            this.capacity = capacity;
2,029✔
88

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

93
            int dictionaryCapacity = ConcurrentDictionarySize.Estimate(this.Capacity);
2,029✔
94

95
            this.dictionary = new ConcurrentDictionary<K, I>(concurrencyLevel, dictionaryCapacity, comparer);
2,029✔
96
            this.itemPolicy = itemPolicy;
2,021✔
97
            this.telemetryPolicy = telemetryPolicy;
2,021✔
98
            this.telemetryPolicy.SetEventSource(this);
2,021✔
99
        }
2,021✔
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,967,166✔
104

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

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

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

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

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

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

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

132
        /// <summary>
133
        /// Gets a collection containing the keys in the cache.
134
        /// </summary>
135
        public ICollection<K> Keys => this.dictionary.Keys;
800✔
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
        {
252✔
147
            foreach (var kvp in this.dictionary)
1,296✔
148
            {
272✔
149
                if (!itemPolicy.ShouldDiscard(kvp.Value))
272✔
150
                { 
260✔
151
                    yield return new KeyValuePair<K, V>(kvp.Key, kvp.Value.Value); 
260✔
152
                }
256✔
153
            }
268✔
154
        }
248✔
155

156
        ///<inheritdoc/>
157
        public bool TryGet(K key, [MaybeNullWhen(false)] out V value)
158
        {
1,799,600,009✔
159
            if (dictionary.TryGetValue(key, out var item))
1,799,600,009✔
160
            {
1,622,581,337✔
161
                return GetOrDiscard(item, out value);
1,622,581,337✔
162
            }
163

164
            value = default;
177,018,672✔
165
            this.telemetryPolicy.IncrementMiss();
177,018,672✔
166
            return false;
177,018,672✔
167
        }
1,799,600,009✔
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,622,581,337✔
174
            if (this.itemPolicy.ShouldDiscard(item))
1,622,581,337✔
175
            {
3,674,921✔
176
                this.Move(item, ItemDestination.Remove, ItemRemovedReason.Evicted);
3,674,921✔
177
                this.telemetryPolicy.IncrementMiss();
3,674,921✔
178
                value = default;
3,674,921✔
179
                return false;
3,674,921✔
180
            }
181

182
            value = item.Value;
1,618,906,416✔
183

184
            this.itemPolicy.Touch(item);
1,618,906,416✔
185
            this.telemetryPolicy.IncrementHit();
1,618,906,416✔
186
            return true;
1,618,906,416✔
187
        }
1,622,581,337✔
188

189
        private bool TryAdd(K key, V value)
190
        {
180,693,299✔
191
            var newItem = this.itemPolicy.CreateItem(key, value);
180,693,299✔
192

193
            if (this.dictionary.TryAdd(key, newItem))
180,693,299✔
194
            {
170,459,941✔
195
                this.hotQueue.Enqueue(newItem);
170,459,941✔
196
                Cycle(Interlocked.Increment(ref counter.hot));
170,459,941✔
197
                return true;
170,459,941✔
198
            }
199

200
            Disposer<V>.Dispose(newItem.Value);
10,233,358✔
201
            return false;
10,233,358✔
202
        }
180,693,299✔
203

204
        ///<inheritdoc/>
205
        public V GetOrAdd(K key, Func<K, V> valueFactory)
206
        {
1,736,965,202✔
207
            while (true)
1,744,652,432✔
208
            {
1,744,652,432✔
209
                if (this.TryGet(key, out var value))
1,744,652,432✔
210
                {
1,608,361,736✔
211
                    return value;
1,608,361,736✔
212
                }
213

214
                // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
215
                value = valueFactory(key);
136,290,696✔
216

217
                if (TryAdd(key, value))
136,290,696✔
218
                {
128,603,466✔
219
                    return value;
128,603,466✔
220
                }
221
            }
7,687,230✔
222
        }
1,736,965,202✔
223

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

243
                // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
244
                value = valueFactory(key, factoryArgument);
14,620,705✔
245

246
                if (TryAdd(key, value))
14,620,705✔
247
                {
13,628,842✔
248
                    return value;
13,628,842✔
249
                }
250
            }
991,863✔
251
        }
16,000,012✔
252

253
        ///<inheritdoc/>
254
        public async ValueTask<V> GetOrAddAsync(K key, Func<K, Task<V>> valueFactory)
255
        {
16,000,304✔
256
            while (true)
16,859,220✔
257
            {
16,859,220✔
258
                if (this.TryGet(key, out var value))
16,859,220✔
259
                {
2,107,330✔
260
                    return value;
2,107,330✔
261
                }
262

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

267
                if (TryAdd(key, value))
14,751,878✔
268
                {
13,892,962✔
269
                    return value;
13,892,962✔
270
                }
271
            }
858,916✔
272
        }
16,000,292✔
273

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

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

295
                if (TryAdd(key, value))
15,030,020✔
296
                {
14,334,671✔
297
                    return value;
14,334,671✔
298
                }
299
            }
695,349✔
300
        }
16,000,276✔
301

302
        /// <summary>
303
        /// Attempts to remove the specified key value pair.
304
        /// </summary>
305
        /// <param name="item">The item to remove.</param>
306
        /// <returns>true if the item was removed successfully; otherwise, false.</returns>
307
        public bool TryRemove(KeyValuePair<K, V> item)
308
        {
18,810,325✔
309
            if (this.dictionary.TryGetValue(item.Key, out var existing))
18,810,325✔
310
            {
2,082,137✔
311
                lock (existing)
2,082,137✔
312
                {
2,082,137✔
313
                    if (EqualityComparer<V>.Default.Equals(existing.Value, item.Value))
2,082,137✔
314
                    {
153,118✔
315
                        var kvp = new KeyValuePair<K, I>(item.Key, existing);
153,118✔
316
#if NET6_0_OR_GREATER
317
                    if (this.dictionary.TryRemove(kvp))
77,369✔
318
#else
319
                        // https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/
320
                        if (((ICollection<KeyValuePair<K, I>>)this.dictionary).Remove(kvp))
75,749✔
321
#endif
322
                        {
144,343✔
323
                            OnRemove(item.Key, kvp.Value, ItemRemovedReason.Removed);
144,343✔
324
                            return true;
144,343✔
325
                        }
326
                    }
8,775✔
327
                }
1,937,794✔
328

329
                // it existed, but we couldn't remove - this means value was replaced afer the TryGetValue (a race)
330
            }
1,937,794✔
331

332
            return false;
18,665,982✔
333
        }
18,810,325✔
334

335
        /// <summary>
336
        /// Attempts to remove and return the value that has the specified key.
337
        /// </summary>
338
        /// <param name="key">The key of the element to remove.</param>
339
        /// <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>
340
        /// <returns>true if the object was removed successfully; otherwise, false.</returns>
341
        public bool TryRemove(K key, [MaybeNullWhen(false)] out V value)
342
        {
16,000,240✔
343
            if (this.dictionary.TryRemove(key, out var item))
16,000,240✔
344
            {
36,504✔
345
                OnRemove(key, item, ItemRemovedReason.Removed);
36,504✔
346
                value = item.Value;
36,504✔
347
                return true;
36,504✔
348
            }
349

350
            value = default;
15,963,736✔
351
            return false;
15,963,736✔
352
        }
16,000,240✔
353

354
        ///<inheritdoc/>
355
        public bool TryRemove(K key)
356
        {
16,000,176✔
357
            return TryRemove(key, out _);
16,000,176✔
358
        }
16,000,176✔
359

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

369
            this.telemetryPolicy.OnItemRemoved(key, item.Value, reason);
184,173,161✔
370

371
            // serialize dispose (common case dispose not thread safe)
372
            lock (item)
184,173,161✔
373
            {
184,173,161✔
374
                Disposer<V>.Dispose(item.Value);
184,173,161✔
375
            }
184,173,161✔
376
        }
184,173,161✔
377

378
        ///<inheritdoc/>
379
        ///<remarks>Note: Calling this method does not affect LRU order.</remarks>
380
        public bool TryUpdate(K key, V value)
381
        {
50,571,800✔
382
            if (this.dictionary.TryGetValue(key, out var existing))
50,571,800✔
383
            {
6,854,576✔
384
                lock (existing)
6,854,576✔
385
                {
6,854,576✔
386
                    if (!existing.WasRemoved)
6,854,576✔
387
                    {
6,746,545✔
388
                        V oldValue = existing.Value;
6,746,545✔
389

390
                        existing.Value = value;
6,746,545✔
391

392
                        this.itemPolicy.Update(existing);
6,746,545✔
393
// backcompat: remove conditional compile
394
#if NETCOREAPP3_0_OR_GREATER
395
                        this.telemetryPolicy.OnItemUpdated(existing.Key, oldValue, existing.Value);
6,746,545✔
396
#endif
397
                        Disposer<V>.Dispose(oldValue);
6,746,545✔
398

399
                        return true;
6,746,545✔
400
                    }
401
                }
108,031✔
402
            }
108,031✔
403

404
            return false;
43,825,255✔
405
        }
50,571,800✔
406

407
        ///<inheritdoc/>
408
        ///<remarks>Note: Updates to existing items do not affect LRU order. Added items are at the top of the LRU.</remarks>
409
        public void AddOrUpdate(K key, V value)
410
        {
18,420,888✔
411
            while (true)
18,571,700✔
412
            {
18,571,700✔
413
                // first, try to update
414
                if (this.TryUpdate(key, value))
18,571,700✔
415
                {
4,680,443✔
416
                    return;
4,680,443✔
417
                }
418

419
                // then try add
420
                var newItem = this.itemPolicy.CreateItem(key, value);
13,891,257✔
421

422
                if (this.dictionary.TryAdd(key, newItem))
13,891,257✔
423
                {
13,740,445✔
424
                    this.hotQueue.Enqueue(newItem);
13,740,445✔
425
                    Cycle(Interlocked.Increment(ref counter.hot));
13,740,445✔
426
                    return;
13,740,445✔
427
                }
428

429
                // if both update and add failed there was a race, try again
430
            }
150,812✔
431
        }
18,420,888✔
432

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

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

461
            if (itemCount < 1 || itemCount > capacity)
244✔
462
                Throw.ArgOutOfRange(nameof(itemCount), "itemCount must be greater than or equal to one, and less than the capacity of the cache.");
8✔
463

464
            // clamp itemCount to number of items actually in the cache
465
            itemCount = Math.Min(itemCount, this.HotCount + this.WarmCount + this.ColdCount);
236✔
466

467
            // don't overlap Clear/Trim/TrimExpired
468
            lock (this.dictionary)
236✔
469
            {
236✔
470
                // first scan each queue for discardable items and remove them immediately. Note this can remove > itemCount items.
471
                int itemsRemoved = TrimAllDiscardedItems();
236✔
472

473
                TrimLiveItems(itemsRemoved, itemCount, ItemRemovedReason.Trimmed);
236✔
474
            }
236✔
475
        }
236✔
476

477
        private void TrimExpired()
478
        {
37✔
479
            if (this.itemPolicy.CanDiscard())
37✔
480
            {
37✔
481
                lock (this.dictionary)
37✔
482
                {
37✔
483
                    this.TrimAllDiscardedItems();
37✔
484
                } 
37✔
485
            }
37✔
486
        }
37✔
487

488
        /// <summary>
489
        /// Trim discarded items from all queues.
490
        /// </summary>
491
        /// <returns>The number of items removed.</returns>
492
        // backcompat: make internal
493
        protected int TrimAllDiscardedItems()
494
        {
273✔
495
            // don't overlap Clear/Trim/TrimExpired
496
            lock (this.dictionary)
273✔
497
            {
273✔
498
                int RemoveDiscardableItems(ConcurrentQueue<I> q, ref int queueCounter)
499
                {
819✔
500
                    int itemsRemoved = 0;
819✔
501
                    int localCount = queueCounter;
819✔
502

503
                    for (int i = 0; i < localCount; i++)
4,994✔
504
                    {
1,678✔
505
                        if (q.TryDequeue(out var item))
1,678✔
506
                        {
1,678✔
507
                            if (this.itemPolicy.ShouldDiscard(item))
1,678✔
508
                            {
231✔
509
                                Interlocked.Decrement(ref queueCounter);
231✔
510
                                this.Move(item, ItemDestination.Remove, ItemRemovedReason.Trimmed);
231✔
511
                                itemsRemoved++;
231✔
512
                            }
231✔
513
                            else if (item.WasRemoved)
1,447✔
514
                            {
24✔
515
                                Interlocked.Decrement(ref queueCounter);
24✔
516
                            }
24✔
517
                            else
518
                            {
1,423✔
519
                                q.Enqueue(item);
1,423✔
520
                            }
1,423✔
521
                        }
1,678✔
522
                    }
1,678✔
523

524
                    return itemsRemoved;
819✔
525
                }
819✔
526

527
                int coldRem = RemoveDiscardableItems(coldQueue, ref this.counter.cold);
273✔
528
                int warmRem = RemoveDiscardableItems(warmQueue, ref this.counter.warm);
273✔
529
                int hotRem = RemoveDiscardableItems(hotQueue, ref this.counter.hot);
273✔
530

531
                if (warmRem > 0)
273✔
532
                {
33✔
533
                    Volatile.Write(ref this.isWarm, false);
33✔
534
                }
33✔
535

536
                return coldRem + warmRem + hotRem;
273✔
537
            }
538
        }
273✔
539

540
        private void TrimLiveItems(int itemsRemoved, int itemCount, ItemRemovedReason reason)
541
        {
1,250,364✔
542
            // When items are touched, they are moved to warm by cycling. Therefore, to guarantee 
543
            // that we can remove itemCount items, we must cycle (2 * capacity.Warm) + capacity.Hot times.
544
            // If clear is called during trimming, it would be possible to get stuck in an infinite
545
            // loop here. The warm + hot limit also guards against this case.
546
            int trimWarmAttempts = 0;
1,250,364✔
547
            int maxWarmHotAttempts = (this.capacity.Warm * 2) + this.capacity.Hot;
1,250,364✔
548

549
            while (itemsRemoved < itemCount && trimWarmAttempts < maxWarmHotAttempts)
12,732,059✔
550
            {
11,481,695✔
551
                if (Volatile.Read(ref this.counter.cold) > 0)
11,481,695✔
552
                {
8,843,354✔
553
                    if (TryRemoveCold(reason) == (ItemDestination.Remove, 0))
8,843,354✔
554
                    {
8,842,823✔
555
                        itemsRemoved++;
8,842,823✔
556
                        trimWarmAttempts = 0;
8,842,823✔
557
                    }
8,842,823✔
558
                    else
559
                    {
531✔
560
                        TrimWarmOrHot(reason);
531✔
561
                    }
531✔
562
                }
8,843,354✔
563
                else
564
                {
2,638,341✔
565
                    TrimWarmOrHot(reason);
2,638,341✔
566
                    trimWarmAttempts++;
2,638,341✔
567
                }
2,638,341✔
568
            }
11,481,695✔
569

570
            if (Volatile.Read(ref this.counter.warm) < this.capacity.Warm)
1,250,364✔
571
            {
698,424✔
572
                Volatile.Write(ref this.isWarm, false);
698,424✔
573
            }
698,424✔
574
        }
1,250,364✔
575

576
        private void TrimWarmOrHot(ItemRemovedReason reason)
577
        {
2,638,872✔
578
            if (Volatile.Read(ref this.counter.warm) > 0)
2,638,872✔
579
            {
888,517✔
580
                CycleWarmUnchecked(reason);
888,517✔
581
            }
888,517✔
582
            else if (Volatile.Read(ref this.counter.hot) > 0)
1,750,355✔
583
            {
1,750,101✔
584
                CycleHotUnchecked(reason);
1,750,101✔
585
            }
1,750,101✔
586
        }
2,638,872✔
587

588
        private void Cycle(int hotCount)
589
        {
184,200,386✔
590
            if (isWarm)
184,200,386✔
591
            {
181,233,795✔
592
                (var dest, var count) = CycleHot(hotCount);
181,233,795✔
593

594
                int cycles = 0;
181,233,795✔
595
                while (cycles++ < 3 && dest != ItemDestination.Remove)
393,660,477✔
596
                {
212,426,682✔
597
                    if (dest == ItemDestination.Warm)
212,426,682✔
598
                    {
34,282,476✔
599
                        (dest, count) = CycleWarm(count);
34,282,476✔
600
                    }
34,282,476✔
601
                    else if (dest == ItemDestination.Cold)
178,144,206✔
602
                    {
178,144,206✔
603
                        (dest, count) = CycleCold(count);
178,144,206✔
604
                    }
178,144,206✔
605
                }
212,426,682✔
606

607
                // If nothing was removed yet, constrain the size of warm and cold by discarding the coldest item.
608
                if (dest != ItemDestination.Remove)
181,233,795✔
609
                {
4,146,249✔
610
                    if (dest == ItemDestination.Warm && count > this.capacity.Warm)
4,146,249✔
611
                    {
2,800,758✔
612
                        count = LastWarmToCold();
2,800,758✔
613
                    }
2,800,758✔
614

615
                    ConstrainCold(count, ItemRemovedReason.Evicted);
4,146,249✔
616
                }
4,146,249✔
617
            }
181,233,795✔
618
            else
619
            {
2,966,591✔
620
                // fill up the warm queue with new items until warm is full.
621
                // else during warmup the cache will only use the hot + cold queues until any item is requested twice.
622
                CycleDuringWarmup(hotCount);
2,966,591✔
623
            }
2,966,591✔
624
        }
184,200,386✔
625

626
        [MethodImpl(MethodImplOptions.NoInlining)]
627
        private void CycleDuringWarmup(int hotCount)
628
        {
2,966,591✔
629
            // do nothing until hot is full
630
            if (hotCount > this.capacity.Hot)
2,966,591✔
631
            {
1,210,379✔
632
                Interlocked.Decrement(ref this.counter.hot);
1,210,379✔
633

634
                if (this.hotQueue.TryDequeue(out var item))
1,210,379!
635
                {
1,210,379✔
636
                    // special case: removed during warmup
637
                    if (item.WasRemoved)
1,210,379✔
638
                    {
108,025✔
639
                        return;
108,025✔
640
                    }
641

642
                    int count = this.Move(item, ItemDestination.Warm, ItemRemovedReason.Evicted);
1,102,354✔
643

644
                    // if warm is now full, overflow to cold and mark as warm
645
                    if (count > this.capacity.Warm)
1,102,354✔
646
                    {
237,916✔
647
                        Volatile.Write(ref this.isWarm, true);
237,916✔
648
                        count = LastWarmToCold();
237,916✔
649
                        ConstrainCold(count, ItemRemovedReason.Evicted);
237,916✔
650
                    }
237,916✔
651
                }
1,102,354✔
652
                else
653
                {
×
654
                    Interlocked.Increment(ref this.counter.hot);
×
655
                }
×
656
            }
1,102,354✔
657
        }
2,966,591✔
658

659
        private (ItemDestination, int) CycleHot(int hotCount)
660
        {
181,233,795✔
661
            if (hotCount > this.capacity.Hot)
181,233,795✔
662
            {
181,232,865✔
663
                return CycleHotUnchecked(ItemRemovedReason.Evicted);
181,232,865✔
664
            }
665

666
            return (ItemDestination.Remove, 0);
930✔
667
        }
181,233,795✔
668

669
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
670
        private (ItemDestination, int) CycleHotUnchecked(ItemRemovedReason removedReason)
671
        {
182,982,966✔
672
            Interlocked.Decrement(ref this.counter.hot);
182,982,966✔
673

674
            if (this.hotQueue.TryDequeue(out var item))
182,982,966!
675
            {
182,982,966✔
676
                var where = this.itemPolicy.RouteHot(item);
182,982,966✔
677
                return (where, this.Move(item, where, removedReason));
182,982,966✔
678
            }
679
            else
680
            {
×
681
                Interlocked.Increment(ref this.counter.hot);
×
682
                return (ItemDestination.Remove, 0);
×
683
            }
684
        }
182,982,966✔
685

686
        private (ItemDestination, int) CycleWarm(int count)
687
        {
34,282,476✔
688
            if (count > this.capacity.Warm)
34,282,476✔
689
            {
34,245,285✔
690
                return CycleWarmUnchecked(ItemRemovedReason.Evicted);
34,245,285✔
691
            }
692

693
            return (ItemDestination.Remove, 0);
37,191✔
694
        }
34,282,476✔
695

696
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
697
        private (ItemDestination, int) CycleWarmUnchecked(ItemRemovedReason removedReason)
698
        {
35,133,802✔
699
            int wc = Interlocked.Decrement(ref this.counter.warm);
35,133,802✔
700

701
            if (this.warmQueue.TryDequeue(out var item))
35,133,802!
702
            {
35,133,802✔
703
                if (item.WasRemoved)
35,133,802✔
704
                {
618,822✔
705
                    return (ItemDestination.Remove, 0);
618,822✔
706
                }
707

708
                var where = this.itemPolicy.RouteWarm(item);
34,514,980✔
709

710
                // When the warm queue is full, we allow an overflow of 1 item before redirecting warm items to cold.
711
                // This only happens when hit rate is high, in which case we can consider all items relatively equal in
712
                // terms of which was least recently used.
713
                if (where == ItemDestination.Warm && wc <= this.capacity.Warm)
34,514,980✔
714
                {
8,550,904✔
715
                    return (ItemDestination.Warm, this.Move(item, where, removedReason));
8,550,904✔
716
                }
717
                else
718
                {
25,964,076✔
719
                    return (ItemDestination.Cold, this.Move(item, ItemDestination.Cold, removedReason));
25,964,076✔
720
                }
721
            }
722
            else
723
            {
×
724
                Interlocked.Increment(ref this.counter.warm);
×
725
                return (ItemDestination.Remove, 0);
×
726
            }
727
        }
35,133,802✔
728

729
        private (ItemDestination, int) CycleCold(int count)
730
        {
178,144,206✔
731
            if (count > this.capacity.Cold)
178,144,206✔
732
            {
172,101,074✔
733
                return TryRemoveCold(ItemRemovedReason.Evicted);
172,101,074✔
734
            }
735

736
            return (ItemDestination.Remove, 0);
6,043,132✔
737
        }
178,144,206✔
738

739
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
740
        private (ItemDestination, int) TryRemoveCold(ItemRemovedReason removedReason)
741
        {
180,944,428✔
742
            Interlocked.Decrement(ref this.counter.cold);
180,944,428✔
743

744
            if (this.coldQueue.TryDequeue(out var item))
180,944,428✔
745
            {
180,944,185✔
746
                var where = this.itemPolicy.RouteCold(item);
180,944,185✔
747

748
                if (where == ItemDestination.Warm && Volatile.Read(ref this.counter.warm) <= this.capacity.Warm)
180,944,185✔
749
                {
2,397,677✔
750
                    return (ItemDestination.Warm, this.Move(item, where, removedReason));
2,397,677✔
751
                }
752
                else
753
                {
178,546,508✔
754
                    this.Move(item, ItemDestination.Remove, removedReason);
178,546,508✔
755
                    return (ItemDestination.Remove, 0);
178,546,508✔
756
                }
757
            }
758
            else
759
            {
243✔
760
                return (ItemDestination.Cold, Interlocked.Increment(ref this.counter.cold));
243✔
761
            }
762
        }
180,944,428✔
763

764
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
765
        private int LastWarmToCold()
766
        {
3,038,674✔
767
            Interlocked.Decrement(ref this.counter.warm);
3,038,674✔
768

769
            if (this.warmQueue.TryDequeue(out var item))
3,038,674!
770
            {
3,038,674✔
771
                var destination = item.WasRemoved ? ItemDestination.Remove : ItemDestination.Cold;
3,038,674✔
772
                return this.Move(item, destination, ItemRemovedReason.Evicted);
3,038,674✔
773
            }
774
            else
775
            {
×
776
                Interlocked.Increment(ref this.counter.warm);
×
777
                return 0;
×
778
            }
779
        }
3,038,674✔
780

781
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
782
        private void ConstrainCold(int coldCount, ItemRemovedReason removedReason)
783
        {
4,384,165✔
784
            if (coldCount > this.capacity.Cold && this.coldQueue.TryDequeue(out var item))
4,384,165✔
785
            {
4,124,221✔
786
                Interlocked.Decrement(ref this.counter.cold);
4,124,221✔
787
                this.Move(item, ItemDestination.Remove, removedReason);
4,124,221✔
788
            }
4,124,221✔
789
        }
4,384,165✔
790

791
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
792
        private int Move(I item, ItemDestination where, ItemRemovedReason removedReason)
793
        {
410,382,532✔
794
            item.WasAccessed = false;
410,382,532✔
795

796
            switch (where)
410,382,532✔
797
            {
798
                case ItemDestination.Warm:
799
                    this.warmQueue.Enqueue(item);
38,187,621✔
800
                    return Interlocked.Increment(ref this.counter.warm);
38,187,621✔
801
                case ItemDestination.Cold:
802
                    this.coldQueue.Enqueue(item);
185,074,186✔
803
                    return Interlocked.Increment(ref this.counter.cold);
185,074,186✔
804
                case ItemDestination.Remove:
805

806
                    var kvp = new KeyValuePair<K, I>(item.Key, item);
187,120,725✔
807

808
#if NET6_0_OR_GREATER
809
                    if (this.dictionary.TryRemove(kvp))
143,606,975✔
810
#else
811
                    // https://devblogs.microsoft.com/pfxteam/little-known-gems-atomic-conditional-removals-from-concurrentdictionary/
812
                    if (((ICollection<KeyValuePair<K, I>>)this.dictionary).Remove(kvp))
43,513,750✔
813
#endif
814
                    {
183,992,314✔
815
                        OnRemove(item.Key, item, removedReason);
183,992,314✔
816
                    }
183,992,314✔
817
                    break;
187,120,725✔
818
            }
819

820
            return 0;
187,120,725✔
821
        }
410,382,532✔
822

823
        /// <summary>Returns an enumerator that iterates through the cache.</summary>
824
        /// <returns>An enumerator for the cache.</returns>
825
        /// <remarks>
826
        /// The enumerator returned from the cache is safe to use concurrently with
827
        /// reads and writes, however it does not represent a moment-in-time snapshot.  
828
        /// The contents exposed through the enumerator may contain modifications
829
        /// made after <see cref="GetEnumerator"/> was called.
830
        /// </remarks>
831
        IEnumerator IEnumerable.GetEnumerator()
832
        {
12✔
833
            return ((ConcurrentLruCore<K, V, I, P, T>)this).GetEnumerator();
12✔
834
        }
12✔
835

836
#if DEBUG
837
        /// <summary>
838
        /// Format the LRU as a string by converting all the keys to strings.
839
        /// </summary>
840
        /// <returns>The LRU formatted as a string.</returns>
841
        internal string FormatLruString()
842
        {
60✔
843
            var sb = new System.Text.StringBuilder();
60✔
844

845
            sb.Append("Hot [");
60✔
846
            sb.Append(string.Join(",", this.hotQueue.Select(n => n.Key.ToString())));
224✔
847
            sb.Append("] Warm [");
60✔
848
            sb.Append(string.Join(",", this.warmQueue.Select(n => n.Key.ToString())));
200✔
849
            sb.Append("] Cold [");
60✔
850
            sb.Append(string.Join(",", this.coldQueue.Select(n => n.Key.ToString())));
180✔
851
            sb.Append(']');
60✔
852

853
            return sb.ToString();
60✔
854
        }
60✔
855
#endif
856

857
        private static CachePolicy CreatePolicy(ConcurrentLruCore<K, V, I, P, T> lru)
858
        {
277✔
859
            var p = new Proxy(lru);
277✔
860

861
            if (typeof(P) == typeof(AfterAccessPolicy<K, V>))
277✔
862
            {
44✔
863
                return new CachePolicy(new Optional<IBoundedPolicy>(p), Optional<ITimePolicy>.None(), new Optional<ITimePolicy>(p), Optional<IDiscreteTimePolicy>.None());
44✔
864
            }
865

866
            // IsAssignableFrom is a jit intrinsic https://github.com/dotnet/runtime/issues/4920
867
            if (typeof(IDiscreteItemPolicy<K, V>).IsAssignableFrom(typeof(P)))
233✔
868
            {
60✔
869
                return new CachePolicy(new Optional<IBoundedPolicy>(p), Optional<ITimePolicy>.None(), Optional<ITimePolicy>.None(), new Optional<IDiscreteTimePolicy>(new DiscreteExpiryProxy(lru)));
60✔
870
            }
871

872
            return new CachePolicy(new Optional<IBoundedPolicy>(p), lru.itemPolicy.CanDiscard() ? new Optional<ITimePolicy>(p) : Optional<ITimePolicy>.None());
173✔
873
        }
277✔
874

875
        private static Optional<ICacheMetrics> CreateMetrics(ConcurrentLruCore<K, V, I, P, T> lru)
876
        {
132✔
877
            if (typeof(T) == typeof(NoTelemetryPolicy<K, V>))
132✔
878
            {
20✔
879
                return Optional<ICacheMetrics>.None();
20✔
880
            }
881

882
            return new(new Proxy(lru));
112✔
883
        }
132✔
884

885
        private static Optional<ICacheEvents<K, V>> CreateEvents(ConcurrentLruCore<K, V, I, P, T> lru)
886
        {
1,056✔
887
            if (typeof(T) == typeof(NoTelemetryPolicy<K, V>))
1,056✔
888
            {
52✔
889
                return Optional<ICacheEvents<K, V>>.None();
52✔
890
            }
891

892
            return new(new Proxy(lru));
1,004✔
893
        }
1,056✔
894

895
        // To get JIT optimizations, policies must be structs.
896
        // If the structs are returned directly via properties, they will be copied. Since  
897
        // telemetryPolicy is a mutable struct, copy is bad. One workaround is to store the 
898
        // state within the struct in an object. Since the struct points to the same object
899
        // it becomes immutable. However, this object is then somewhere else on the 
900
        // heap, which slows down the policies with hit counter logic in benchmarks. Likely
901
        // this approach keeps the structs data members in the same CPU cache line as the LRU.
902
        // backcompat: remove conditional compile
903
#if NETCOREAPP3_0_OR_GREATER
904
        [DebuggerDisplay("Hit = {Hits}, Miss = {Misses}, Upd = {Updated}, Evict = {Evicted}")]
905
#else
906
        [DebuggerDisplay("Hit = {Hits}, Miss = {Misses}, Evict = {Evicted}")]
907
#endif
908
        private class Proxy : ICacheMetrics, ICacheEvents<K, V>, IBoundedPolicy, ITimePolicy
909
        {
910
            private readonly ConcurrentLruCore<K, V, I, P, T> lru;
911

912
            public Proxy(ConcurrentLruCore<K, V, I, P, T> lru)
1,393✔
913
            {
1,393✔
914
                this.lru = lru;
1,393✔
915
            }
1,393✔
916

917
            public double HitRatio => lru.telemetryPolicy.HitRatio;
8✔
918

919
            public long Total => lru.telemetryPolicy.Total;
4✔
920

921
            public long Hits => lru.telemetryPolicy.Hits;
24✔
922

923
            public long Misses => lru.telemetryPolicy.Misses;
24✔
924

925
            public long Evicted => lru.telemetryPolicy.Evicted;
32✔
926

927
// backcompat: remove conditional compile
928
#if NETCOREAPP3_0_OR_GREATER
929
            public long Updated => lru.telemetryPolicy.Updated;
8✔
930
#endif
931
            public int Capacity => lru.Capacity;
108✔
932

933
            public TimeSpan TimeToLive => lru.itemPolicy.TimeToLive;
16✔
934

935
            public event EventHandler<ItemRemovedEventArgs<K, V>> ItemRemoved
936
            {
937
                add { this.lru.telemetryPolicy.ItemRemoved += value; }
180✔
938
                remove { this.lru.telemetryPolicy.ItemRemoved -= value; }
24✔
939
            }
940

941
// backcompat: remove conditional compile
942
#if NETCOREAPP3_0_OR_GREATER
943
            public event EventHandler<ItemUpdatedEventArgs<K, V>> ItemUpdated
944
            {
945
                add { this.lru.telemetryPolicy.ItemUpdated += value; }
108✔
946
                remove { this.lru.telemetryPolicy.ItemUpdated -= value; }
12✔
947
            }
948
#endif
949
            public void Trim(int itemCount)
950
            {
40✔
951
                lru.Trim(itemCount);
40✔
952
            }
40✔
953

954
            public void TrimExpired()
955
            {
29✔
956
                lru.TrimExpired();
29✔
957
            }
29✔
958
        }
959

960
        private class DiscreteExpiryProxy : IDiscreteTimePolicy
961
        {
962
            private readonly ConcurrentLruCore<K, V, I, P, T> lru;
963

964
            public DiscreteExpiryProxy(ConcurrentLruCore<K, V, I, P, T> lru)
60✔
965
            {
60✔
966
                this.lru = lru;
60✔
967
            }
60✔
968

969
            public void TrimExpired()
970
            {
8✔
971
                lru.TrimExpired();
8✔
972
            }
8✔
973

974
            public bool TryGetTimeToExpire<TKey>(TKey key, out TimeSpan timeToLive)
975
            {
12✔
976
                if (key is K k && lru.dictionary.TryGetValue(k, out var item))
12✔
977
                {
4✔
978
                    LongTickCountLruItem<K, V>? tickItem = item as LongTickCountLruItem<K, V>;
4✔
979
                    timeToLive = (new Duration(tickItem!.TickCount) - Duration.SinceEpoch()).ToTimeSpan();
4✔
980
                    return true;
4✔
981
                }
982

983
                timeToLive = default;
8✔
984
                return false;
8✔
985
            }
12✔
986
        }
987
    }
988
}
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