aboutsummaryrefslogtreecommitdiff
path: root/MultiplayerToolkit/Assets/MultiplayerToolkit/ObjectPool.cs
blob: e42cdd6cda82855fc9d850b567b1873e9da10349 (plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

namespace MultiplayerToolkit
{
    /// <summary>
    ///     A fairly simple object pool for items that will be created a lot.
    /// </summary>
    /// <typeparam name="T">The type that is pooled.</typeparam>
    /// <threadsafety static="true" instance="true"/>
    public sealed class ObjectPool<T> where T : IRecyclable
    {
        private int numberCreated;
        public int NumberCreated { get { return numberCreated; } }

        public int NumberInUse { get { return this.inuse.Count; } }
        public int NumberNotInUse { get { return this.pool.Count; } }
        public int Size { get { return this.NumberInUse + this.NumberNotInUse; } }

#if HAZEL_BAG
        private readonly ConcurrentBag<T> pool = new ConcurrentBag<T>();
#else
        private readonly List<T> pool = new List<T>();
#endif

        // Unavailable objects
        private readonly ConcurrentDictionary<T, bool> inuse = new ConcurrentDictionary<T, bool>();

        /// <summary>
        ///     The generator for creating new objects.
        /// </summary>
        /// <returns></returns>
        private readonly Func<T> objectFactory;
        
        /// <summary>
        ///     Internal constructor for our ObjectPool.
        /// </summary>
        internal ObjectPool(Func<T> objectFactory)
        {
            this.objectFactory = objectFactory;
        }

        /// <summary>
        ///     Returns a pooled object of type T, if none are available another is created.
        /// </summary>
        /// <returns>An instance of T.</returns>
        internal T GetObject()
        {
#if HAZEL_BAG
            if (!pool.TryTake(out T item))
            {
                Interlocked.Increment(ref numberCreated);
                item = objectFactory.Invoke();
            }
#else
            T item;
            lock (this.pool)
            {
                if (this.pool.Count > 0)
                {
                    var idx = this.pool.Count - 1;
                    item = this.pool[idx];
                    this.pool.RemoveAt(idx);
                }
                else
                {
                    Interlocked.Increment(ref numberCreated);
                    item = objectFactory.Invoke();
                }
            }
#endif

            if (!inuse.TryAdd(item, true))
            {
                throw new Exception("Duplicate pull " + typeof(T).Name);
            }

            return item;
        }

        /// <summary>
        ///     Returns an object to the pool.
        /// </summary>
        /// <param name="item">The item to return.</param>
        internal void PutObject(T item)
        {
            if (inuse.TryRemove(item, out bool b))
            {
#if HAZEL_BAG
                pool.Add(item);
#else
                lock (this.pool)
                {
                    pool.Add(item);
                }
#endif
            }
            else
            {
#if DEBUG
                throw new Exception("Duplicate add " + typeof(T).Name);
#endif
            }
        }
    }
}