Skip to content

Commit

Permalink
Changed how frequent maintenance removes expired items.
Browse files Browse the repository at this point in the history
  • Loading branch information
niemyjski committed Mar 19, 2024
1 parent bc5bbf2 commit e45c500
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/Foundatio/Caching/InMemoryCacheClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -883,9 +883,14 @@ private async Task CompactAsync()
(string Key, long LastAccessTicks, long InstanceNumber) oldest = (null, Int64.MaxValue, 0);
foreach (var kvp in _memory)
{
if (kvp.Value.LastAccessTicks < oldest.LastAccessTicks
|| (kvp.Value.LastAccessTicks == oldest.LastAccessTicks && kvp.Value.InstanceNumber < oldest.InstanceNumber))
bool isExpired = kvp.Value.ExpiresAt < SystemClock.UtcNow;
if (isExpired ||
kvp.Value.LastAccessTicks < oldest.LastAccessTicks ||
(kvp.Value.LastAccessTicks == oldest.LastAccessTicks && kvp.Value.InstanceNumber < oldest.InstanceNumber))
oldest = (kvp.Key, kvp.Value.LastAccessTicks, kvp.Value.InstanceNumber);

if (isExpired)
break;
}

_logger.LogDebug("Removing cache entry {Key} due to cache exceeding max item count limit.", oldest);
Expand All @@ -904,12 +909,15 @@ private async Task DoMaintenanceAsync()

var utcNow = SystemClock.UtcNow.AddMilliseconds(50);

// Remove expired items and items that are infrequently accessed as they may be updated by add.
long lastAccessMaximumTicks = utcNow.AddMilliseconds(-300).Ticks;

try
{
foreach (var kvp in _memory.ToArray())
{
var expiresAt = kvp.Value.ExpiresAt;
if (expiresAt <= utcNow)
bool lastAccessTimeIsInfrequent = kvp.Value.LastAccessTicks < lastAccessMaximumTicks;
if (lastAccessTimeIsInfrequent && kvp.Value.ExpiresAt <= utcNow)
{
_logger.LogDebug("DoMaintenance: Removing expired key {Key}", kvp.Key);
RemoveExpiredKey(kvp.Key);
Expand Down

0 comments on commit e45c500

Please sign in to comment.