ObjectPool.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. #pragma warning disable CA1822
  2. #nullable disable
  3. // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  4. // define TRACE_LEAKS to get additional diagnostics that can lead to the leak sources. note: it will
  5. // make everything about 2-3x slower
  6. //
  7. // #define TRACE_LEAKS
  8. // define DETECT_LEAKS to detect possible leaks
  9. // #if DEBUG
  10. // #define DETECT_LEAKS //for now always enable DETECT_LEAKS in debug.
  11. // #endif
  12. using System.Diagnostics;
  13. #if DETECT_LEAKS
  14. using System.Runtime.CompilerServices;
  15. #endif
  16. namespace Jint.Pooling
  17. {
  18. /// <summary>
  19. /// Generic implementation of object pooling pattern with predefined pool size limit. The main
  20. /// purpose is that limited number of frequently used objects can be kept in the pool for
  21. /// further recycling.
  22. ///
  23. /// Notes:
  24. /// 1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there
  25. /// is no space in the pool, extra returned objects will be dropped.
  26. ///
  27. /// 2) it is implied that if object was obtained from a pool, the caller will return it back in
  28. /// a relatively short time. Keeping checked out objects for long durations is ok, but
  29. /// reduces usefulness of pooling. Just new up your own.
  30. ///
  31. /// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice.
  32. /// Rationale:
  33. /// If there is no intent for reusing the object, do not use pool - just use "new".
  34. /// </summary>
  35. internal sealed class ObjectPool<T> where T : class
  36. {
  37. [DebuggerDisplay("{Value,nq}")]
  38. private struct Element
  39. {
  40. internal T Value;
  41. }
  42. /// <remarks>
  43. /// Not using System.Func{T} because this file is linked into the (debugger) Formatter,
  44. /// which does not have that type (since it compiles against .NET 2.0).
  45. /// </remarks>
  46. internal delegate T Factory();
  47. // Storage for the pool objects. The first item is stored in a dedicated field because we
  48. // expect to be able to satisfy most requests from it.
  49. private T _firstItem;
  50. private readonly Element[] _items;
  51. // factory is stored for the lifetime of the pool. We will call this only when pool needs to
  52. // expand. compared to "new T()", Func gives more flexibility to implementers and faster
  53. // than "new T()".
  54. private readonly Factory _factory;
  55. #if DETECT_LEAKS
  56. private static readonly ConditionalWeakTable<T, LeakTracker> leakTrackers = new ConditionalWeakTable<T, LeakTracker>();
  57. private class LeakTracker : IDisposable
  58. {
  59. private volatile bool disposed;
  60. #if TRACE_LEAKS
  61. internal volatile object Trace = null;
  62. #endif
  63. public void Dispose()
  64. {
  65. disposed = true;
  66. GC.SuppressFinalize(this);
  67. }
  68. private string GetTrace()
  69. {
  70. #if TRACE_LEAKS
  71. return Trace == null ? "" : Trace.ToString();
  72. #else
  73. return "Leak tracing information is disabled. Define TRACE_LEAKS on ObjectPool`1.cs to get more info \n";
  74. #endif
  75. }
  76. ~LeakTracker()
  77. {
  78. if (!this.disposed && !Environment.HasShutdownStarted)
  79. {
  80. var trace = GetTrace();
  81. // If you are seeing this message it means that object has been allocated from the pool
  82. // and has not been returned back. This is not critical, but turns pool into rather
  83. // inefficient kind of "new".
  84. Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nPool detected potential leaking of {typeof(T)}. \n Location of the leak: \n {GetTrace()} TRACEOBJECTPOOLLEAKS_END");
  85. }
  86. }
  87. }
  88. #endif
  89. internal ObjectPool(Factory factory)
  90. : this(factory, Environment.ProcessorCount * 2)
  91. { }
  92. internal ObjectPool(Factory factory, int size)
  93. {
  94. Debug.Assert(size >= 1);
  95. _factory = factory;
  96. _items = new Element[size - 1];
  97. }
  98. private T CreateInstance()
  99. {
  100. var inst = _factory();
  101. return inst;
  102. }
  103. /// <summary>
  104. /// Produces an instance.
  105. /// </summary>
  106. /// <remarks>
  107. /// Search strategy is a simple linear probing which is chosen for it cache-friendliness.
  108. /// Note that Free will try to store recycled objects close to the start thus statistically
  109. /// reducing how far we will typically search.
  110. /// </remarks>
  111. internal T Allocate()
  112. {
  113. // PERF: Examine the first element. If that fails, AllocateSlow will look at the remaining elements.
  114. // Note that the initial read is optimistically not synchronized. That is intentional.
  115. // We will interlock only when we have a candidate. in a worst case we may miss some
  116. // recently returned objects. Not a big deal.
  117. T inst = _firstItem;
  118. if (inst is not null)
  119. {
  120. _firstItem = null;
  121. return inst;
  122. }
  123. inst = AllocateSlow();
  124. #if DETECT_LEAKS
  125. var tracker = new LeakTracker();
  126. leakTrackers.Add(inst, tracker);
  127. #if TRACE_LEAKS
  128. var frame = CaptureStackTrace();
  129. tracker.Trace = frame;
  130. #endif
  131. #endif
  132. return inst;
  133. }
  134. private T AllocateSlow()
  135. {
  136. var items = _items;
  137. for (int i = 0; i < items.Length; i++)
  138. {
  139. T inst = items[i].Value;
  140. if (inst is not null)
  141. {
  142. items[i].Value = null;
  143. return inst;
  144. }
  145. }
  146. return CreateInstance();
  147. }
  148. /// <summary>
  149. /// Returns objects to the pool.
  150. /// </summary>
  151. /// <remarks>
  152. /// Search strategy is a simple linear probing which is chosen for it cache-friendliness.
  153. /// Note that Free will try to store recycled objects close to the start thus statistically
  154. /// reducing how far we will typically search in Allocate.
  155. /// </remarks>
  156. internal void Free(T obj)
  157. {
  158. Validate(obj);
  159. ForgetTrackedObject(obj);
  160. if (_firstItem is null)
  161. {
  162. // Intentionally not using interlocked here.
  163. // In a worst case scenario two objects may be stored into same slot.
  164. // It is very unlikely to happen and will only mean that one of the objects will get collected.
  165. _firstItem = obj;
  166. }
  167. else
  168. {
  169. FreeSlow(obj);
  170. }
  171. }
  172. private void FreeSlow(T obj)
  173. {
  174. var items = _items;
  175. for (int i = 0; i < items.Length; i++)
  176. {
  177. if (ReferenceEquals(items[i].Value, null))
  178. {
  179. // Intentionally not using interlocked here.
  180. // In a worst case scenario two objects may be stored into same slot.
  181. // It is very unlikely to happen and will only mean that one of the objects will get collected.
  182. items[i].Value = obj;
  183. break;
  184. }
  185. }
  186. }
  187. /// <summary>
  188. /// Removes an object from leak tracking.
  189. ///
  190. /// This is called when an object is returned to the pool. It may also be explicitly
  191. /// called if an object allocated from the pool is intentionally not being returned
  192. /// to the pool. This can be of use with pooled arrays if the consumer wants to
  193. /// return a larger array to the pool than was originally allocated.
  194. /// </summary>
  195. [Conditional("DEBUG")]
  196. internal void ForgetTrackedObject(T old, T replacement = null)
  197. {
  198. #if DETECT_LEAKS
  199. LeakTracker tracker;
  200. if (leakTrackers.TryGetValue(old, out tracker))
  201. {
  202. tracker.Dispose();
  203. leakTrackers.Remove(old);
  204. }
  205. else
  206. {
  207. var trace = CaptureStackTrace();
  208. Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nObject of type {typeof(T)} was freed, but was not from pool. \n Callstack: \n {trace} TRACEOBJECTPOOLLEAKS_END");
  209. }
  210. if (replacement != null)
  211. {
  212. tracker = new LeakTracker();
  213. leakTrackers.Add(replacement, tracker);
  214. }
  215. #endif
  216. }
  217. #if DETECT_LEAKS
  218. private static Lazy<Type> _stackTraceType = new Lazy<Type>(() => Type.GetType("System.Diagnostics.StackTrace"));
  219. private static object CaptureStackTrace()
  220. {
  221. return Activator.CreateInstance(_stackTraceType.Value);
  222. }
  223. #endif
  224. [Conditional("DEBUG")]
  225. private void Validate(object obj)
  226. {
  227. Debug.Assert(obj != null, "freeing null?");
  228. Debug.Assert(_firstItem != obj, "freeing twice?");
  229. var items = _items;
  230. for (int i = 0; i < items.Length; i++)
  231. {
  232. var value = items[i].Value;
  233. if (value is null)
  234. {
  235. return;
  236. }
  237. Debug.Assert(value != obj, "freeing twice?");
  238. }
  239. }
  240. }
  241. }