Skip to content

Commit

Permalink
Remove fast-path closures from EventBasedLRUCache (#2170)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub authored Jul 27, 2023
1 parent 31d60d5 commit ac018e4
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/Microsoft.IdentityModel.Tokens/EventBasedLRUCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -390,10 +390,12 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime)
cacheItem.ExpirationTime = expirationTime;
if (_maintainLRU)
{
var localCacheItem = cacheItem; // avoid closure when !_maintainLRU
var localThis = this;
AddActionToEventQueue(() =>
{
_doubleLinkedList.Remove(cacheItem);
_doubleLinkedList.AddFirst(cacheItem);
localThis._doubleLinkedList.Remove(localCacheItem);
localThis._doubleLinkedList.AddFirst(localCacheItem);
});
}
}
Expand All @@ -416,11 +418,13 @@ public bool SetValue(TKey key, TValue value, DateTime expirationTime)
// add the new node to the _doubleLinkedList if _maintainLRU == true
if (_maintainLRU)
{
var localNewCacheItem = newCacheItem; // avoid closure when !_maintainLRU
var localThis = this;
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);
localThis._doubleLinkedList.Remove(localNewCacheItem);
localThis._doubleLinkedList.AddFirst(localNewCacheItem);
});
}

Expand Down Expand Up @@ -492,10 +496,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 +522,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 ac018e4

Please sign in to comment.