Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,16 @@ public Config()
}


[Params(200, 1_000)]
public int NumberOfLocks;
[ParamsSource(nameof(Configurations))]
public (int NumberOfLocks, int Contention) Setting { get; set; }
public (int NumberOfLocks, int Contention)[] Configurations { get; } =
[
(200, 100),
(200, 10_000),
(10_000, 100)
];

[Params(100, 1_000)]
public int Contention;

[Params(0, 10)]
public int GuidReversals;
[Params(0, 1, 5)] public int GuidReversals { get; set; }

private StandardMemoryLocker _StandardMemoryLocker = null!;
private ParallelQuery<Task> _StandardMemoryLockerTasks = null!;
Expand Down Expand Up @@ -65,13 +67,13 @@ public void Setup()
[IterationSetup]
public void IterationSetup()
{
List<int> _shuffledIntegerList = [.. Enumerable.Range(0, Contention * NumberOfLocks)];
List<int> _shuffledIntegerList = [.. Enumerable.Range(0, Setting.Contention * Setting.NumberOfLocks)];
Shuffle(_shuffledIntegerList);

_StandardMemoryLockerTasks = _shuffledIntegerList
.Select(async i =>
{
var key = (i % NumberOfLocks).ToString();
var key = (i % Setting.NumberOfLocks).ToString();

var mylock = await _StandardMemoryLocker.AcquireLockAsync(null!, null!, null!, key, TimeSpan.FromSeconds(5), null, default).ConfigureAwait(false);
Operation();
Expand All @@ -81,7 +83,7 @@ public void IterationSetup()
_ProbabilisticMemoryLockerTasks = _shuffledIntegerList
.Select(async i =>
{
var key = (i % NumberOfLocks).ToString();
var key = (i % Setting.NumberOfLocks).ToString();

var mylock = await _ProbabilisticMemoryLocker.AcquireLockAsync(null!, null!, null!, key, TimeSpan.FromSeconds(5), null, default).ConfigureAwait(false);
Operation();
Expand All @@ -91,7 +93,7 @@ public void IterationSetup()
_ExperimentalMemoryLockerTasks = _shuffledIntegerList
.Select(async i =>
{
var key = (i % NumberOfLocks).ToString();
var key = (i % Setting.NumberOfLocks).ToString();

var mylock = await _ExperimentalMemoryLocker.AcquireLockAsync(null!, null!, null!, key, TimeSpan.FromSeconds(5), null, default).ConfigureAwait(false);
Operation();
Expand All @@ -101,7 +103,7 @@ public void IterationSetup()
_AsyncKeyedMemoryLockerTasks = _shuffledIntegerList
.Select(async i =>
{
var key = (i % NumberOfLocks).ToString();
var key = (i % Setting.NumberOfLocks).ToString();

var mylock = await _AsyncKeyedMemoryLocker.AcquireLockAsync(null!, null!, null!, key, TimeSpan.FromSeconds(5), null, default).ConfigureAwait(false);
Operation();
Expand All @@ -111,7 +113,7 @@ public void IterationSetup()
_StripedAsyncKeyedMemoryLockerTasks = _shuffledIntegerList
.Select(async i =>
{
var key = (i % NumberOfLocks).ToString();
var key = (i % Setting.NumberOfLocks).ToString();

var mylock = await _StripedAsyncKeyedMemoryLocker.AcquireLockAsync(null!, null!, null!, key, TimeSpan.FromSeconds(5), null, default).ConfigureAwait(false);
Operation();
Expand All @@ -121,10 +123,6 @@ public void IterationSetup()

private async Task RunTests(ParallelQuery<Task> tasks)
{
if (NumberOfLocks == Contention)
{
throw new Exception("Thrown on purpose");
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}

Expand Down Expand Up @@ -202,7 +200,7 @@ public async Task TestLockAsyncKeyedLock()
await RunTests(_AsyncKeyedMemoryLockerTasks).ConfigureAwait(false);
}

//[Benchmark]
[Benchmark]
public async Task TestLockStripedAsyncKeyedLock()
{
await RunTests(_StripedAsyncKeyedMemoryLockerTasks).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,68 +1,80 @@
using AsyncKeyedLock;
using Microsoft.Extensions.Logging;
using System.Runtime.CompilerServices;

namespace ZiggyCreatures.Caching.Fusion.Locking.AsyncKeyed;

/// <summary>
/// An implementation of <see cref="IFusionCacheMemoryLocker"/> based on AsyncKeyedLocker.
/// </summary>
public sealed class AsyncKeyedMemoryLocker
: IFusionCacheMemoryLocker
: IFusionCacheMemoryLocker
{
private readonly AsyncKeyedLocker<string> _locker;
private readonly AsyncKeyedLocker<string> _locker;

/// <summary>
/// Initializes a new instance of the <see cref="AsyncKeyedLocker{TKey}"/> class.
/// </summary>
public AsyncKeyedMemoryLocker(AsyncKeyedLockOptions? options = null)
{
options ??= new AsyncKeyedLockOptions();
/// <summary>
/// Initializes a new instance of the <see cref="AsyncKeyedLocker{TKey}"/> class.
/// </summary>
public AsyncKeyedMemoryLocker(AsyncKeyedLockOptions? options = null)
{
options ??= new AsyncKeyedLockOptions();

_locker = new AsyncKeyedLocker<string>(options);
}
_locker = new AsyncKeyedLocker<string>(options);
}

/// <inheritdoc/>
public async ValueTask<object?> AcquireLockAsync(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
return await _locker.LockOrNullAsync(key, timeout, token).ConfigureAwait(false);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ValueTask<object?> AcquireLockAsync(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
var acquireTask = _locker.LockOrNullAsync(key, timeout, token);

/// <inheritdoc/>
public object? AcquireLock(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
return _locker.LockOrNull(key, timeout, token);
}
return acquireTask.IsCompletedSuccessfully ?
new ValueTask<object?>(acquireTask.Result) :
AwaitAcquireLockAsync(acquireTask);
}

/// <inheritdoc/>
public void ReleaseLock(string cacheName, string cacheInstanceId, string operationId, string key, object? lockObj, ILogger? logger)
{
if (lockObj is null)
return;
private static async ValueTask<object?> AwaitAcquireLockAsync(ValueTask<IDisposable?> acquireTask)
{
return await acquireTask.ConfigureAwait(false);
}

try
{
((IDisposable)lockObj).Dispose();
}
catch (Exception exc)
{
if (logger?.IsEnabled(LogLevel.Warning) ?? false)
logger.Log(LogLevel.Warning, exc, "FUSION [N={CacheName} I={CacheInstanceId}] (O={CacheOperationId} K={CacheKey}): an error occurred while trying to release an AsyncKeyedLock result in the memory locker", cacheName, cacheInstanceId, operationId, key);
}
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public object? AcquireLock(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
return _locker.LockOrNull(key, timeout, token);
}

// IDISPOSABLE
private bool disposedValue;
/// <inheritdoc/>
public void ReleaseLock(string cacheName, string cacheInstanceId, string operationId, string key, object? lockObj, ILogger? logger)
{
if (lockObj is null)
return;

/// <inheritdoc/>
public void Dispose()
{
if (disposedValue)
{
return;
}
try
{
((IDisposable)lockObj).Dispose();
}
catch (Exception exc)
{
if (logger?.IsEnabled(LogLevel.Warning) ?? false)
logger.Log(LogLevel.Warning, exc, "FUSION [N={CacheName} I={CacheInstanceId}] (O={CacheOperationId} K={CacheKey}): an error occurred while trying to release an AsyncKeyedLock result in the memory locker", cacheName, cacheInstanceId, operationId, key);
}
}

_locker?.Dispose();
// IDISPOSABLE
private bool disposedValue;

disposedValue = true;
}
/// <inheritdoc/>
public void Dispose()
{
if (disposedValue)
{
return;
}

_locker?.Dispose();

disposedValue = true;
}
}
Original file line number Diff line number Diff line change
@@ -1,56 +1,67 @@
using AsyncKeyedLock;
using Microsoft.Extensions.Logging;
using System.Runtime.CompilerServices;

namespace ZiggyCreatures.Caching.Fusion.Locking.AsyncKeyed;

/// <summary>
/// An implementation of <see cref="IFusionCacheMemoryLocker"/> based on StripedAsyncKeyedLocker.
/// </summary>
public sealed class StripedAsyncKeyedMemoryLocker
: IFusionCacheMemoryLocker
: IFusionCacheMemoryLocker
{
private readonly StripedAsyncKeyedLocker<string> _locker;

/// <summary>
/// Initializes a new instance of the <see cref="StripedAsyncKeyedLocker{TKey}"/> class.
/// </summary>
public StripedAsyncKeyedMemoryLocker(int numberOfStripes = 4049, int maxCount = 1, IEqualityComparer<string>? comparer = null)
{
_locker = new StripedAsyncKeyedLocker<string>(numberOfStripes, maxCount, comparer);
}

/// <inheritdoc/>
public async ValueTask<object?> AcquireLockAsync(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
return await _locker.LockOrNullAsync(key, timeout, token).ConfigureAwait(false);
}

/// <inheritdoc/>
public object? AcquireLock(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
return _locker.LockOrNull(key, timeout, token);
}

/// <inheritdoc/>
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReleaseLock(string cacheName, string cacheInstanceId, string operationId, string key, object? lockObj, ILogger? logger)
{
if (lockObj is null)
return;

try
{
((IDisposable)lockObj).Dispose();
}
catch (Exception exc)
{
if (logger?.IsEnabled(LogLevel.Warning) ?? false)
logger.Log(LogLevel.Warning, exc, "FUSION [N={CacheName} I={CacheInstanceId}] (O={CacheOperationId} K={CacheKey}): an error occurred while trying to release an AsyncKeyedLock result in the memory locker", cacheName, cacheInstanceId, operationId, key);
}
}

/// <inheritdoc/>
public void Dispose()
{
}
private readonly StripedAsyncKeyedLocker<string> _locker;

/// <summary>
/// Initializes a new instance of the <see cref="StripedAsyncKeyedLocker{TKey}"/> class.
/// </summary>
public StripedAsyncKeyedMemoryLocker(int numberOfStripes = 4049, int maxCount = 1, IEqualityComparer<string>? comparer = null)
{
_locker = new StripedAsyncKeyedLocker<string>(numberOfStripes, maxCount, comparer);
}

/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ValueTask<object?> AcquireLockAsync(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
var acquireTask = _locker.LockOrNullAsync(key, timeout, token);

return acquireTask.IsCompletedSuccessfully ?
new ValueTask<object?>(acquireTask.Result) :
AwaitAcquireLockAsync(acquireTask);
}

private static async ValueTask<object?> AwaitAcquireLockAsync(ValueTask<StripedAsyncKeyedLockReleaser?> acquireTask)
{
return await acquireTask.ConfigureAwait(false);
}

/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public object? AcquireLock(string cacheName, string cacheInstanceId, string operationId, string key, TimeSpan timeout, ILogger? logger, CancellationToken token)
{
return _locker.LockOrNull(key, timeout, token);
}

/// <inheritdoc/>
public void ReleaseLock(string cacheName, string cacheInstanceId, string operationId, string key, object? lockObj, ILogger? logger)
{
if (lockObj is null)
return;

try
{
((IDisposable)lockObj).Dispose();
}
catch (Exception exc)
{
if (logger?.IsEnabled(LogLevel.Warning) ?? false)
logger.Log(LogLevel.Warning, exc, "FUSION [N={CacheName} I={CacheInstanceId}] (O={CacheOperationId} K={CacheKey}): an error occurred while trying to release an AsyncKeyedLock result in the memory locker", cacheName, cacheInstanceId, operationId, key);
}
}

/// <inheritdoc/>
public void Dispose()
{
}
}
Loading