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

bitfaster / BitFaster.Caching / 13341524291

15 Feb 2025 03:53AM UTC coverage: 98.952% (-0.2%) from 99.168%
13341524291

Pull #638

github

web-flow
Merge 42248d7f5 into 56d0d7868
Pull Request #638: provide a net9 build target

1120 of 1146 branches covered (97.73%)

Branch coverage included in aggregate %.

8 of 9 new or added lines in 2 files covered. (88.89%)

9 existing lines in 1 file now uncovered.

4829 of 4866 relevant lines covered (99.24%)

51719223.19 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,141✔
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,590,372✔
159
            if (dictionary.TryGetValue(key, out var item))
1,799,590,372✔
160
            {
1,622,576,959✔
161
                return GetOrDiscard(item, out value);
1,622,576,959✔
162
            }
163

164
            value = default;
177,013,413✔
165
            this.telemetryPolicy.IncrementMiss();
177,013,413✔
166
            return false;
177,013,413✔
167
        }
1,799,590,372✔
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,576,959✔
174
            if (this.itemPolicy.ShouldDiscard(item))
1,622,576,959✔
175
            {
3,867,715✔
176
                this.Move(item, ItemDestination.Remove, ItemRemovedReason.Evicted);
3,867,715✔
177
                this.telemetryPolicy.IncrementMiss();
3,867,715✔
178
                value = default;
3,867,715✔
179
                return false;
3,867,715✔
180
            }
181

182
            value = item.Value;
1,618,709,244✔
183

184
            this.itemPolicy.Touch(item);
1,618,709,244✔
185
            this.telemetryPolicy.IncrementHit();
1,618,709,244✔
186
            return true;
1,618,709,244✔
187
        }
1,622,576,959✔
188

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

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

200
            Disposer<V>.Dispose(newItem.Value);
10,155,071✔
201
            return false;
10,155,071✔
202
        }
180,880,742✔
203

204
        ///<inheritdoc/>
205
        public V GetOrAdd(K key, Func<K, V> valueFactory)
206
        {
1,737,033,860✔
207
            while (true)
1,745,085,643✔
208
            {
1,745,085,643✔
209
                if (this.TryGet(key, out var value))
1,745,085,643✔
210
                {
1,608,889,885✔
211
                    return value;
1,608,889,885✔
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,195,758✔
216

217
                if (TryAdd(key, value))
136,195,758✔
218
                {
128,143,975✔
219
                    return value;
128,143,975✔
220
                }
221
            }
8,051,783✔
222
        }
1,737,033,860✔
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,764,477✔
237
            {
16,764,477✔
238
                if (this.TryGet(key, out var value))
16,764,477✔
239
                {
2,037,682✔
240
                    return value;
2,037,682✔
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,726,795✔
245

246
                if (TryAdd(key, value))
14,726,795✔
247
                {
13,962,330✔
248
                    return value;
13,962,330✔
249
                }
250
            }
764,465✔
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,624,768✔
257
            {
16,624,768✔
258
                if (this.TryGet(key, out var value))
16,624,768✔
259
                {
1,513,541✔
260
                    return value;
1,513,541✔
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);
15,111,227✔
266

267
                if (TryAdd(key, value))
15,111,215✔
268
                {
14,486,751✔
269
                    return value;
14,486,751✔
270
                }
271
            }
624,464✔
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,714,635✔
286
            {
16,714,635✔
287
                if (this.TryGet(key, out var value))
16,714,635✔
288
                {
1,867,661✔
289
                    return value;
1,867,661✔
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);
14,846,974✔
294

295
                if (TryAdd(key, value))
14,846,974✔
296
                {
14,132,615✔
297
                    return value;
14,132,615✔
298
                }
299
            }
714,359✔
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,436,544✔
309
            if (this.dictionary.TryGetValue(item.Key, out var existing))
18,436,544✔
310
            {
1,857,005✔
311
                lock (existing)
1,857,005✔
312
                {
1,857,005✔
313
                    if (EqualityComparer<V>.Default.Equals(existing.Value, item.Value))
1,857,005✔
314
                    {
147,451✔
315
                        var kvp = new KeyValuePair<K, I>(item.Key, existing);
147,451✔
316
#if NET6_0_OR_GREATER
317
                    if (this.dictionary.TryRemove(kvp))
78,447✔
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))
69,004✔
321
#endif
322
                        {
141,296✔
323
                            OnRemove(item.Key, kvp.Value, ItemRemovedReason.Removed);
141,296✔
324
                            return true;
141,296✔
325
                        }
326
                    }
6,155✔
327
                }
1,715,709✔
328

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

332
            return false;
18,295,248✔
333
        }
18,436,544✔
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
            {
27,079✔
345
                OnRemove(key, item, ItemRemovedReason.Removed);
27,079✔
346
                value = item.Value;
27,079✔
347
                return true;
27,079✔
348
            }
349

350
            value = default;
15,973,161✔
351
            return false;
15,973,161✔
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,949,069✔
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,949,069✔
367
            item.WasRemoved = true;
184,949,069✔
368

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

371
            // serialize dispose (common case dispose not thread safe)
372
            lock (item)
184,949,069✔
373
            {
184,949,069✔
374
                Disposer<V>.Dispose(item.Value);
184,949,069✔
375
            }
184,949,069✔
376
        }
184,949,069✔
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,498,857✔
382
            if (this.dictionary.TryGetValue(key, out var existing))
50,498,857✔
383
            {
6,484,513✔
384
                lock (existing)
6,484,513✔
385
                {
6,484,513✔
386
                    if (!existing.WasRemoved)
6,484,513✔
387
                    {
6,365,377✔
388
                        V oldValue = existing.Value;
6,365,377✔
389

390
                        existing.Value = value;
6,365,377✔
391

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

399
                        return true;
6,365,377✔
400
                    }
401
                }
119,136✔
402
            }
119,136✔
403

404
            return false;
44,133,480✔
405
        }
50,498,857✔
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,353,353✔
411
            while (true)
18,498,757✔
412
            {
18,498,757✔
413
                // first, try to update
414
                if (this.TryUpdate(key, value))
18,498,757✔
415
                {
4,102,741✔
416
                    return;
4,102,741✔
417
                }
418

419
                // then try add
420
                var newItem = this.itemPolicy.CreateItem(key, value);
14,396,016✔
421

422
                if (this.dictionary.TryAdd(key, newItem))
14,396,016✔
423
                {
14,250,612✔
424
                    this.hotQueue.Enqueue(newItem);
14,250,612✔
425
                    Cycle(Interlocked.Increment(ref counter.hot));
14,250,612✔
426
                    return;
14,250,612✔
427
                }
428

429
                // if both update and add failed there was a race, try again
430
            }
145,404✔
431
        }
18,353,353✔
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
                            {
234✔
509
                                Interlocked.Decrement(ref queueCounter);
234✔
510
                                this.Move(item, ItemDestination.Remove, ItemRemovedReason.Trimmed);
234✔
511
                                itemsRemoved++;
234✔
512
                            }
234✔
513
                            else if (item.WasRemoved)
1,444✔
514
                            {
24✔
515
                                Interlocked.Decrement(ref queueCounter);
24✔
516
                            }
24✔
517
                            else
518
                            {
1,420✔
519
                                q.Enqueue(item);
1,420✔
520
                            }
1,420✔
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,719,203✔
550
            {
11,468,839✔
551
                if (Volatile.Read(ref this.counter.cold) > 0)
11,468,839✔
552
                {
8,866,400✔
553
                    if (TryRemoveCold(reason) == (ItemDestination.Remove, 0))
8,866,400✔
554
                    {
8,865,875✔
555
                        itemsRemoved++;
8,865,875✔
556
                        trimWarmAttempts = 0;
8,865,875✔
557
                    }
8,865,875✔
558
                    else
559
                    {
525✔
560
                        TrimWarmOrHot(reason);
525✔
561
                    }
525✔
562
                }
8,866,400✔
563
                else
564
                {
2,602,439✔
565
                    TrimWarmOrHot(reason);
2,602,439✔
566
                    trimWarmAttempts++;
2,602,439✔
567
                }
2,602,439✔
568
            }
11,468,839✔
569

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

576
        private void TrimWarmOrHot(ItemRemovedReason reason)
577
        {
2,602,964✔
578
            if (Volatile.Read(ref this.counter.warm) > 0)
2,602,964✔
579
            {
866,608✔
580
                CycleWarmUnchecked(reason);
866,608✔
581
            }
866,608✔
582
            else if (Volatile.Read(ref this.counter.hot) > 0)
1,736,356✔
583
            {
1,736,134✔
584
                CycleHotUnchecked(reason);
1,736,134✔
585
            }
1,736,134✔
586
        }
2,602,964✔
587

588
        private void Cycle(int hotCount)
589
        {
184,976,283✔
590
            if (isWarm)
184,976,283✔
591
            {
182,048,365✔
592
                (var dest, var count) = CycleHot(hotCount);
182,048,365✔
593

594
                int cycles = 0;
182,048,365✔
595
                while (cycles++ < 3 && dest != ItemDestination.Remove)
394,721,420✔
596
                {
212,673,055✔
597
                    if (dest == ItemDestination.Warm)
212,673,055✔
598
                    {
33,261,179✔
599
                        (dest, count) = CycleWarm(count);
33,261,179✔
600
                    }
33,261,179✔
601
                    else if (dest == ItemDestination.Cold)
179,411,876✔
602
                    {
179,411,876✔
603
                        (dest, count) = CycleCold(count);
179,411,876✔
604
                    }
179,411,876✔
605
                }
212,673,055✔
606

607
                // If nothing was removed yet, constrain the size of warm and cold by discarding the coldest item.
608
                if (dest != ItemDestination.Remove)
182,048,365✔
609
                {
3,779,830✔
610
                    if (dest == ItemDestination.Warm && count > this.capacity.Warm)
3,779,830✔
611
                    {
2,410,000✔
612
                        count = LastWarmToCold();
2,410,000✔
613
                    }
2,410,000✔
614

615
                    ConstrainCold(count, ItemRemovedReason.Evicted);
3,779,830✔
616
                }
3,779,830✔
617
            }
182,048,365✔
618
            else
619
            {
2,927,918✔
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,927,918✔
623
            }
2,927,918✔
624
        }
184,976,283✔
625

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

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

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

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

659
        private (ItemDestination, int) CycleHot(int hotCount)
660
        {
182,048,365✔
661
            if (hotCount > this.capacity.Hot)
182,048,365✔
662
            {
182,047,859✔
663
                return CycleHotUnchecked(ItemRemovedReason.Evicted);
182,047,859✔
664
            }
665

666
            return (ItemDestination.Remove, 0);
506✔
667
        }
182,048,365✔
668

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

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

686
        private (ItemDestination, int) CycleWarm(int count)
687
        {
33,261,179✔
688
            if (count > this.capacity.Warm)
33,261,179✔
689
            {
33,223,536✔
690
                return CycleWarmUnchecked(ItemRemovedReason.Evicted);
33,223,536✔
691
            }
692

693
            return (ItemDestination.Remove, 0);
37,643✔
694
        }
33,261,179✔
695

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

701
            if (this.warmQueue.TryDequeue(out var item))
34,090,144!
702
            {
34,090,144✔
703
                if (item.WasRemoved)
34,090,144✔
704
                {
574,890✔
705
                    return (ItemDestination.Remove, 0);
574,890✔
706
                }
707

708
                var where = this.itemPolicy.RouteWarm(item);
33,515,254✔
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)
33,515,254✔
714
                {
7,387,395✔
715
                    return (ItemDestination.Warm, this.Move(item, where, removedReason));
7,387,395✔
716
                }
717
                else
718
                {
26,127,859✔
719
                    return (ItemDestination.Cold, this.Move(item, ItemDestination.Cold, removedReason));
26,127,859✔
720
                }
721
            }
722
            else
723
            {
×
724
                Interlocked.Increment(ref this.counter.warm);
×
725
                return (ItemDestination.Remove, 0);
×
726
            }
727
        }
34,090,144✔
728

729
        private (ItemDestination, int) CycleCold(int count)
730
        {
179,411,876✔
731
            if (count > this.capacity.Cold)
179,411,876✔
732
            {
173,298,584✔
733
                return TryRemoveCold(ItemRemovedReason.Evicted);
173,298,584✔
734
            }
735

736
            return (ItemDestination.Remove, 0);
6,113,292✔
737
        }
179,411,876✔
738

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

744
            if (this.coldQueue.TryDequeue(out var item))
182,164,984✔
745
            {
182,164,765✔
746
                var where = this.itemPolicy.RouteCold(item);
182,164,765✔
747

748
                if (where == ItemDestination.Warm && Volatile.Read(ref this.counter.warm) <= this.capacity.Warm)
182,164,765✔
749
                {
2,481,402✔
750
                    return (ItemDestination.Warm, this.Move(item, where, removedReason));
2,481,402✔
751
                }
752
                else
753
                {
179,683,363✔
754
                    this.Move(item, ItemDestination.Remove, removedReason);
179,683,363✔
755
                    return (ItemDestination.Remove, 0);
179,683,363✔
756
                }
757
            }
758
            else
759
            {
219✔
760
                return (ItemDestination.Cold, Interlocked.Increment(ref this.counter.cold));
219✔
761
            }
762
        }
182,164,984✔
763

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

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

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

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

796
            switch (where)
410,798,910✔
797
            {
798
                case ItemDestination.Warm:
799
                    this.warmQueue.Enqueue(item);
36,739,512✔
800
                    return Interlocked.Increment(ref this.counter.warm);
36,739,512✔
801
                case ItemDestination.Cold:
802
                    this.coldQueue.Enqueue(item);
185,937,094✔
803
                    return Interlocked.Increment(ref this.counter.cold);
185,937,094✔
804
                case ItemDestination.Remove:
805

806
                    var kvp = new KeyValuePair<K, I>(item.Key, item);
188,122,304✔
807

808
#if NET6_0_OR_GREATER
809
                    if (this.dictionary.TryRemove(kvp))
143,673,318✔
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))
44,448,986✔
813
#endif
814
                    {
184,780,694✔
815
                        OnRemove(item.Key, item, removedReason);
184,780,694✔
816
                    }
184,780,694✔
817
                    break;
188,122,304✔
818
            }
819

820
            return 0;
188,122,304✔
821
        }
410,798,910✔
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
#if NET9_0_OR_GREATER
896

897
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
898
        private static bool IsCompatibleKey<TAlternateKey>(ConcurrentDictionary<K, I> d)
899
            where TAlternateKey : notnull, allows ref struct
900
        {
901
            return d.Comparer is IAlternateEqualityComparer<TAlternateKey, K>;
902
        }
903

904
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
905
        private static IAlternateEqualityComparer<TAlternateKey, K> GetAlternateComparer<TAlternateKey>(ConcurrentDictionary<K, I> d)
906
             where TAlternateKey : notnull, allows ref struct
907
        {
908
            Debug.Assert(IsCompatibleKey<TAlternateKey>(d));
909
            return Unsafe.As<IAlternateEqualityComparer<TAlternateKey, K>>(d.Comparer!);
910
        }
911

912
        public IAlternateCache<TAlternateKey, K, V> GetAlternateCache<TAlternateKey>() where TAlternateKey : notnull, allows ref struct
913
        {
914
            if (!IsCompatibleKey<TAlternateKey>(this.dictionary))
915
            {
916
                Throw.IncompatibleComparer();
917
            }
918

919
            return new AlternateCache<TAlternateKey>(this);
920
        }
921

922
        public bool TryGetAlternateCache<TAlternateKey>([MaybeNullWhen(false)] out IAlternateCache<TAlternateKey, K, V> lookup) where TAlternateKey : notnull, allows ref struct
923
        {
924
            if (IsCompatibleKey<TAlternateKey>(this.dictionary))
925
            {
926
                lookup = new AlternateCache<TAlternateKey>(this);
927
                return true;
928
            }
929

930
            lookup = default;
931
            return false;
932
        }
933

934
        // Rough idea of alternate cache interface
935
        // Note: we need a sync and async variant, plumbed into ICache and IAsyncCache.
936
        public interface IAlternateCache<TAlternateKey, K, V> where TAlternateKey : notnull, allows ref struct
937
        {
938
            bool TryGet(TAlternateKey key, [MaybeNullWhen(false)] out V value);
939

940
            bool TryRemove(TAlternateKey key, [MaybeNullWhen(false)] out K actualKey, [MaybeNullWhen(false)] out V value);
941

942
            V GetOrAdd(TAlternateKey altKey, Func<TAlternateKey, V> valueFactory);
943

944
            V GetOrAdd<TArg>(TAlternateKey altKey, Func<TAlternateKey, TArg, V> valueFactory, TArg factoryArgument);
945

946
            // TryUpdate
947
            // AddOrUpdate
948
        }
949

950
        internal readonly struct AlternateCache<TAlternateKey> : IAlternateCache<TAlternateKey, K, V> where TAlternateKey : notnull, allows ref struct
951
        {
952
            /// <summary>Initialize the instance. The dictionary must have already been verified to have a compatible comparer.</summary>
953
            internal AlternateCache(ConcurrentLruCore<K, V, I, P, T> lru)
954
            {
955
                Debug.Assert(lru is not null);
956
                Debug.Assert(IsCompatibleKey<TAlternateKey>(lru.dictionary));
957
                Lru = lru;
958
            }
959

960
            internal ConcurrentLruCore<K, V, I, P, T> Lru { get; }
961

962
            public bool TryGet(TAlternateKey key, [MaybeNullWhen(false)] out V value)
963
            {
964
                var alternate = this.Lru.dictionary.GetAlternateLookup<TAlternateKey>();
965

966
                if (alternate.TryGetValue(key, out var item))
967
                {
968
                    return Lru.GetOrDiscard(item, out value);
969
                }
970

971
                value = default;
972
                Lru.telemetryPolicy.IncrementMiss();
973
                return false;
974
            }
975

976
            public bool TryRemove(TAlternateKey key, [MaybeNullWhen(false)] out K actualKey, [MaybeNullWhen(false)] out V value)
977
            {
978
                var alternate = this.Lru.dictionary.GetAlternateLookup<TAlternateKey>();
979

980
                if (alternate.TryGetValue(key, out var item))
981
                {
982
                    Lru.OnRemove(item.Key, item, ItemRemovedReason.Removed);
983
                    actualKey = item.Key;
984
                    value = item.Value;
985
                    return true;
986
                }
987

988
                actualKey = default;
989
                value = default;
990
                return false;
991
            }
992

993
            public V GetOrAdd(TAlternateKey altKey, Func<TAlternateKey, V> valueFactory)
994
            {
995
                var alternate = this.Lru.dictionary.GetAlternateLookup<TAlternateKey>();
996

997
                while (true)
998
                {
999
                    if (alternate.TryGetValue(altKey, out var item))
1000
                    {
1001
                        return item.Value;
1002
                    }
1003

1004
                    // We cannot avoid allocating the key since it is required for item policy etc. Thus fall back to Lru for add.
1005
                    // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
1006
                    K key = GetAlternateComparer<TAlternateKey>(this.Lru.dictionary).Create(altKey);
1007
                    V value = valueFactory(altKey);
1008
                    if (Lru.TryAdd(key, value))
1009
                    {
1010
                        return value;
1011
                    }
1012
                }
1013
            }
1014

1015
            public V GetOrAdd<TArg>(TAlternateKey altKey, Func<TAlternateKey, TArg, V> valueFactory, TArg factoryArgument)
1016
            {
1017
                var alternate = this.Lru.dictionary.GetAlternateLookup<TAlternateKey>();
1018

1019
                while (true)
1020
                {
1021
                    if (alternate.TryGetValue(altKey, out var item))
1022
                    {
1023
                        return item.Value;
1024
                    }
1025

1026
                    // We cannot avoid allocating the key since it is required for item policy etc. Thus fall back to Lru for add.
1027
                    // The value factory may be called concurrently for the same key, but the first write to the dictionary wins.
1028
                    K key = GetAlternateComparer<TAlternateKey>(this.Lru.dictionary).Create(altKey);
1029
                    V value = valueFactory(altKey, factoryArgument);
1030
                    if (Lru.TryAdd(key, value))
1031
                    {
1032
                        return value;
1033
                    }
1034
                }
1035
            }
1036
        }
1037

1038
#endif
1039

1040
        // To get JIT optimizations, policies must be structs.
1041
        // If the structs are returned directly via properties, they will be copied. Since  
1042
        // telemetryPolicy is a mutable struct, copy is bad. One workaround is to store the 
1043
        // state within the struct in an object. Since the struct points to the same object
1044
        // it becomes immutable. However, this object is then somewhere else on the 
1045
        // heap, which slows down the policies with hit counter logic in benchmarks. Likely
1046
        // this approach keeps the structs data members in the same CPU cache line as the LRU.
1047
        // backcompat: remove conditional compile
1048
#if NETCOREAPP3_0_OR_GREATER
1049
        [DebuggerDisplay("Hit = {Hits}, Miss = {Misses}, Upd = {Updated}, Evict = {Evicted}")]
1050
#else
1051
        [DebuggerDisplay("Hit = {Hits}, Miss = {Misses}, Evict = {Evicted}")]
1052
#endif
1053
        private class Proxy : ICacheMetrics, ICacheEvents<K, V>, IBoundedPolicy, ITimePolicy
1054
        {
1055
            private readonly ConcurrentLruCore<K, V, I, P, T> lru;
1056

1057
            public Proxy(ConcurrentLruCore<K, V, I, P, T> lru)
1,393✔
1058
            {
1,393✔
1059
                this.lru = lru;
1,393✔
1060
            }
1,393✔
1061

1062
            public double HitRatio => lru.telemetryPolicy.HitRatio;
8✔
1063

1064
            public long Total => lru.telemetryPolicy.Total;
4✔
1065

1066
            public long Hits => lru.telemetryPolicy.Hits;
24✔
1067

1068
            public long Misses => lru.telemetryPolicy.Misses;
24✔
1069

1070
            public long Evicted => lru.telemetryPolicy.Evicted;
32✔
1071

1072
// backcompat: remove conditional compile
1073
#if NETCOREAPP3_0_OR_GREATER
1074
            public long Updated => lru.telemetryPolicy.Updated;
8✔
1075
#endif
1076
            public int Capacity => lru.Capacity;
108✔
1077

1078
            public TimeSpan TimeToLive => lru.itemPolicy.TimeToLive;
16✔
1079

1080
            public event EventHandler<ItemRemovedEventArgs<K, V>> ItemRemoved
1081
            {
1082
                add { this.lru.telemetryPolicy.ItemRemoved += value; }
180✔
1083
                remove { this.lru.telemetryPolicy.ItemRemoved -= value; }
24✔
1084
            }
1085

1086
// backcompat: remove conditional compile
1087
#if NETCOREAPP3_0_OR_GREATER
1088
            public event EventHandler<ItemUpdatedEventArgs<K, V>> ItemUpdated
1089
            {
1090
                add { this.lru.telemetryPolicy.ItemUpdated += value; }
108✔
1091
                remove { this.lru.telemetryPolicy.ItemUpdated -= value; }
12✔
1092
            }
1093
#endif
1094
            public void Trim(int itemCount)
1095
            {
40✔
1096
                lru.Trim(itemCount);
40✔
1097
            }
40✔
1098

1099
            public void TrimExpired()
1100
            {
29✔
1101
                lru.TrimExpired();
29✔
1102
            }
29✔
1103
        }
1104

1105
        private class DiscreteExpiryProxy : IDiscreteTimePolicy
1106
        {
1107
            private readonly ConcurrentLruCore<K, V, I, P, T> lru;
1108

1109
            public DiscreteExpiryProxy(ConcurrentLruCore<K, V, I, P, T> lru)
60✔
1110
            {
60✔
1111
                this.lru = lru;
60✔
1112
            }
60✔
1113

1114
            public void TrimExpired()
1115
            {
8✔
1116
                lru.TrimExpired();
8✔
1117
            }
8✔
1118

1119
            public bool TryGetTimeToExpire<TKey>(TKey key, out TimeSpan timeToLive)
1120
            {
12✔
1121
                if (key is K k && lru.dictionary.TryGetValue(k, out var item))
12✔
1122
                {
4✔
1123
                    LongTickCountLruItem<K, V>? tickItem = item as LongTickCountLruItem<K, V>;
4✔
1124
                    timeToLive = (new Duration(tickItem!.TickCount) - Duration.SinceEpoch()).ToTimeSpan();
4✔
1125
                    return true;
4✔
1126
                }
1127

1128
                timeToLive = default;
8✔
1129
                return false;
8✔
1130
            }
12✔
1131
        }
1132
    }
1133
}
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