Skip to content

Commit

Permalink
Add automatic pool resizing
Browse files Browse the repository at this point in the history
Exanite committed Jan 23, 2025
1 parent 6a3b55a commit 1b4095c
Showing 3 changed files with 16 additions and 5 deletions.
16 changes: 12 additions & 4 deletions Pooling/Pool.cs
Original file line number Diff line number Diff line change
@@ -41,15 +41,17 @@ public Pool(
Action<T>? onAcquire = null,
Action<T>? onRelease = null,
Action<T>? onDestroy = null,
int maxInactive = 100)
int initialMaxInactive = 100,
bool allowResizing = true)
{
if (maxInactive <= 0)
if (initialMaxInactive <= 0)
{
throw new ArgumentException("Max inactive must be greater than 0", nameof(maxInactive));
throw new ArgumentException("initialMaxInactive must be greater than 0", nameof(initialMaxInactive));
}

values = new Queue<T>();
usageInfo.MaxInactive = maxInactive;
usageInfo.MaxInactive = initialMaxInactive;
usageInfo.AllowResizing = allowResizing;

this.create = () =>
{
@@ -73,6 +75,12 @@ public Pool(
{
usageInfo.DestroyCount++;
onDestroy?.Invoke(value);

if (!IsDisposed && usageInfo.AllowResizing && usageInfo.DestroyCount > (ulong)usageInfo.MaxInactive)
{
usageInfo.MaxInactive *= 2;
usageInfo.MaxInactiveResizeCount++;
}
};

Pools.AddPool(this, false);
3 changes: 3 additions & 0 deletions Pooling/PoolUsageInfo.cs
Original file line number Diff line number Diff line change
@@ -4,6 +4,9 @@ public struct PoolUsageInfo
{
public int MaxInactive;

public bool AllowResizing;
public int MaxInactiveResizeCount;

public int TotalCount;
public int ActiveCount;
public int InactiveCount;
2 changes: 1 addition & 1 deletion Tests/PoolTests.cs
Original file line number Diff line number Diff line change
@@ -74,7 +74,7 @@ public void Acquire_EnforcesMaxInactiveLimit()
const int acquireCountA = 20;
const int maxInactive = 5;

var pool = new Pool<A>(create: () => new A(), maxInactive: maxInactive);
var pool = new Pool<A>(create: () => new A(), initialMaxInactive: maxInactive, allowResizing: false);
var active = new List<A>();

Assert.AreEqual(maxInactive, pool.UsageInfo.MaxInactive);

0 comments on commit 1b4095c

Please sign in to comment.