Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove fast-path closures from EventBasedLRUCache #2170

Merged
merged 1 commit into from
Jul 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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