-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pool.cs
86 lines (70 loc) · 2.2 KB
/
Pool.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
namespace Binocle
{
/// <summary>
/// simple static class that can be used to pool any object
/// </summary>
public static class Pool<T> where T : new()
{
private static Queue<T> _objectQueue = new Queue<T>(10);
/// <summary>
/// warms up the cache filling it with a max of cacheCount objects
/// </summary>
/// <param name="cacheCount">new cache count</param>
public static void warmCache(int cacheCount)
{
cacheCount -= _objectQueue.Count;
if (cacheCount > 0)
{
for (var i = 0; i < cacheCount; i++)
_objectQueue.Enqueue(new T());
}
}
/// <summary>
/// trims the cache down to cacheCount items
/// </summary>
/// <param name="cacheCount">Cache count.</param>
public static void trimCache(int cacheCount)
{
while (cacheCount > _objectQueue.Count)
_objectQueue.Dequeue();
}
/// <summary>
/// clears out the cache
/// </summary>
public static void clearCache()
{
_objectQueue.Clear();
}
/// <summary>
/// pops an item off the stack if available creating a new item as necessary
/// </summary>
public static T obtain()
{
if (_objectQueue.Count > 0)
return _objectQueue.Dequeue();
return new T();
}
/// <summary>
/// pushes an item back on the stack
/// </summary>
/// <param name="obj">Object.</param>
public static void free(T obj)
{
_objectQueue.Enqueue(obj);
if (obj is IPoolable)
((IPoolable)obj).reset();
}
}
/// <summary>
/// Objects implementing this interface will have {@link #reset()} called when passed to {@link #push(Object)}
/// </summary>
public interface IPoolable
{
/// <summary>
/// Resets the object for reuse. Object references should be nulled and fields may be set to default values
/// </summary>
void reset();
}
}