Skip to content

Commit

Permalink
Remove fast-path closures from EventBasedLRUCache
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub committed Jul 26, 2023
1 parent 28f89d2 commit 92fbb8a
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -390,10 +390,11 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime)
cacheItem.ExpirationTime = expirationTime;
if (_maintainLRU)
{
var localCacheItem = cacheItem; // avoid closure when !_maintainLRU
AddActionToEventQueue(() =>
{
_doubleLinkedList.Remove(cacheItem);
_doubleLinkedList.AddFirst(cacheItem);
_doubleLinkedList.Remove(localCacheItem);
_doubleLinkedList.AddFirst(localCacheItem);
});
}
}
Expand All @@ -416,11 +417,12 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime)
// add the new node to the _doubleLinkedList if _maintainLRU == true
if (_maintainLRU)
{
var localCacheItem = cacheItem; // avoid closure when !_maintainLRU
AddActionToEventQueue(() =>
{
// Add a remove operation in case two threads are trying to add the same value. Only the second remove will succeed in this case.
_doubleLinkedList.Remove(newCacheItem);
_doubleLinkedList.AddFirst(newCacheItem);
_doubleLinkedList.Remove(localCacheItem);
_doubleLinkedList.AddFirst(localCacheItem);
});
}

Expand Down Expand Up @@ -492,10 +494,12 @@ public bool TryGetValue(TKey key, out TValue value)
// make sure node hasn't been removed by a different thread
if (_maintainLRU)
{
var localCacheItem = cacheItem; // avoid closure on fast path or when !_maintainLRU
var localThis = this;
AddActionToEventQueue(() =>
{
_doubleLinkedList.Remove(cacheItem);
_doubleLinkedList.AddFirst(cacheItem);
localThis._doubleLinkedList.Remove(localCacheItem);
localThis._doubleLinkedList.AddFirst(localCacheItem);
});
}

Expand All @@ -516,7 +520,11 @@ public bool TryRemove(TKey key, out TValue value)
}

if (_maintainLRU)
AddActionToEventQueue(() => _doubleLinkedList.Remove(cacheItem));
{
var localCacheItem = cacheItem; // avoid closure on fast path or when !_maintainLRU
var localThis = this;
AddActionToEventQueue(() => localThis._doubleLinkedList.Remove(localCacheItem));
}

value = cacheItem.Value;
OnItemRemoved?.Invoke(cacheItem.Value);
Expand Down

0 comments on commit 92fbb8a

Please sign in to comment.