Skip to content

Instantly share code, notes, and snippets.

@StephenCleary
Created September 28, 2014 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StephenCleary/eb455de7d1c79dfc7d5f to your computer and use it in GitHub Desktop.
Save StephenCleary/eb455de7d1c79dfc7d5f to your computer and use it in GitHub Desktop.
Singly-linked list object pool with the list members embedded in the contained object.
public sealed class MyObject : IDisposable
{
/// <summary>
/// Used by the pool.
/// </summary>
private MyObject _next;
// TODO: Add other members here.
public static MyObject Create()
{
var result = Pool.Instance.TryGet();
if (result != null)
return result;
return new MyObject();
}
public void Dispose()
{
Pool.Instance.Put(this);
}
private sealed class Pool
{
private readonly object _mutex = new object();
private MyObject _first;
public MyObject TryGet()
{
lock (_mutex)
{
var result = _first;
if (result == null)
return result;
_first = _first._next;
return result;
}
}
public void Put(MyObject element)
{
lock (_mutex)
{
element._next = _first;
_first = element;
}
}
public static readonly Pool Instance = new Pool();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment