diff --git a/algorithms/data-structures/ObjectPool.cs b/algorithms/data-structures/ObjectPool.cs new file mode 100644 index 0000000..afa5745 --- /dev/null +++ b/algorithms/data-structures/ObjectPool.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Concurrent; + +namespace OctaneDownloadEngine +{ + public class ObjectPool + { + private ConcurrentBag _objects; + private readonly Func _objectGenerator; + + public ObjectPool(Func objectGenerator) + { + _objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator)); + _objects = new ConcurrentBag(); + } + + public T Get() => _objects.TryTake(out T item) ? item : _objectGenerator(); + + public void Return(T item) => _objects.Add(item); + + public void Empty() + { + _objects = null; + } + } +}