Created
September 28, 2014 15:58
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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