|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.Linq; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using BitFaster.Caching.Atomic; |
| 5 | +using FluentAssertions; |
| 6 | +using Xunit; |
| 7 | + |
| 8 | +namespace BitFaster.Caching.UnitTests.Atomic |
| 9 | +{ |
| 10 | + [Collection("Soak")] |
| 11 | + public class ScopedAsyncAtomicFactorySoakTests |
| 12 | + { |
| 13 | + private const int threads = 4; |
| 14 | + private const int items = 1024; |
| 15 | + |
| 16 | + [Fact] |
| 17 | + public async Task WhenGetOrAddIsConcurrentValuesCreatedAtomically() |
| 18 | + { |
| 19 | + var dictionary = new ConcurrentDictionary<int, ScopedAsyncAtomicFactory<int, Disposable>>(concurrencyLevel: threads, capacity: items); |
| 20 | + var counters = new int[threads]; |
| 21 | + |
| 22 | + await Threaded.RunAsync(threads, async (r) => |
| 23 | + { |
| 24 | + for (int i = 0; i < items; i++) |
| 25 | + { |
| 26 | + while (true) |
| 27 | + { |
| 28 | + var scope = dictionary.GetOrAdd(i, k => new ScopedAsyncAtomicFactory<int, Disposable>()); |
| 29 | + var (success, lifetime) = await scope.TryCreateLifetimeAsync(i, k => { counters[r]++; return Task.FromResult(new Scoped<Disposable>(new Disposable(k))); }); |
| 30 | + |
| 31 | + if (success) |
| 32 | + { |
| 33 | + using (lifetime) |
| 34 | + { |
| 35 | + lifetime.Value.IsDisposed.Should().BeFalse(); |
| 36 | + } |
| 37 | + |
| 38 | + break; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + }); |
| 43 | + |
| 44 | + counters.Sum(x => x).Should().Be(items); |
| 45 | + } |
| 46 | + |
| 47 | + [Fact] |
| 48 | + public async Task WhenGetOrAddAndDisposeIsConcurrentLifetimesAreValid() |
| 49 | + { |
| 50 | + var dictionary = new ConcurrentDictionary<int, ScopedAsyncAtomicFactory<int, Disposable>>(concurrencyLevel: threads, capacity: items); |
| 51 | + |
| 52 | + await Threaded.RunAsync(threads, async (r) => |
| 53 | + { |
| 54 | + for (int i = 0; i < items; i++) |
| 55 | + { |
| 56 | + if (dictionary.TryRemove(i, out var d)) |
| 57 | + { |
| 58 | + d.Dispose(); |
| 59 | + } |
| 60 | + |
| 61 | + while (true) |
| 62 | + { |
| 63 | + var scope = dictionary.GetOrAdd(i, k => new ScopedAsyncAtomicFactory<int, Disposable>()); |
| 64 | + var (success, lifetime) = await scope.TryCreateLifetimeAsync(i, k => { return Task.FromResult(new Scoped<Disposable>(new Disposable(k))); }); |
| 65 | + |
| 66 | + if (success) |
| 67 | + { |
| 68 | + using (lifetime) |
| 69 | + { |
| 70 | + lifetime.Value.IsDisposed.Should().BeFalse(); |
| 71 | + } |
| 72 | + |
| 73 | + break; |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | + }); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments