Skip to content

Commit

Permalink
Fixed WeakReferenceKey to use hashcode for comparisons
Browse files Browse the repository at this point in the history
  • Loading branch information
tippmar-nr committed Feb 4, 2025
1 parent d242c8e commit f1a5a9c
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,35 +11,28 @@ namespace NewRelic.Agent.Extensions.Caching
/// <typeparam name="T"></typeparam>
public class WeakReferenceKey<T> where T : class
{
private readonly int _hashCode;
private WeakReference<T> WeakReference { get; }

public WeakReferenceKey(T cacheKey)
{
WeakReference = new WeakReference<T>(cacheKey);
_hashCode = cacheKey.GetHashCode(); // store the hashcode since we use it in the Equals method and the object could have been GC'd by the time we need to look for it
}

public override bool Equals(object obj)
{
if (obj is WeakReferenceKey<T> otherKey)
{
if (WeakReference.TryGetTarget(out var thisTarget) &&
otherKey.WeakReference.TryGetTarget(out var otherTarget))
{
return ReferenceEquals(thisTarget, otherTarget);
}
return otherKey.GetHashCode() == _hashCode;
}

return false;
}

public override int GetHashCode()
{
if (WeakReference.TryGetTarget(out var target))
{
return target.GetHashCode();
}

return 0;
return _hashCode;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,24 +93,6 @@ public void GetHashCode_ShouldReturnDifferentHashCodeForDifferentObjects()
Assert.That(hashCode1, Is.Not.EqualTo(hashCode2));
}

[Test]
public async Task GetHashCode_ShouldReturnZeroIfTargetIsGarbageCollected()
{
// Arrange
var weakRefKey = GetWeakReferenceKey();

// Act
Assert.That(weakRefKey.Value, Is.Not.Null);
// force garbage collection
GC.Collect();
GC.WaitForPendingFinalizers();
await Task.Delay(500);
GC.Collect(); // Force another collection

// Assert
Assert.That(weakRefKey.GetHashCode(), Is.EqualTo(0));
}

[Test]
public async Task Value_ShouldReturnNullIfTargetIsGarbageCollected()
{
Expand Down

0 comments on commit f1a5a9c

Please sign in to comment.