2
0

ObjectPool.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. /// <summary>
  18. /// Generic implementation of object pooling pattern with predefined pool size limit. The main
  19. /// purpose is that limited number of frequently used objects can be kept in the pool for
  20. /// further recycling.
  21. ///
  22. /// Notes:
  23. /// 1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there
  24. /// is no space in the pool, extra returned objects will be dropped.
  25. ///
  26. /// 2) it is implied that if object was obtained from a pool, the caller will return it back in
  27. /// a relatively short time. Keeping checked out objects for long durations is ok, but
  28. /// reduces usefulness of pooling. Just new up your own.
  29. ///
  30. /// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice.
  31. /// Rationale:
  32. /// If there is no intent for reusing the object, do not use pool - just use "new".
  33. /// </summary>
  34. internal sealed class ObjectPool<T> where T : class
  35. {
  36. [DebuggerDisplay("{Value,nq}")]
  37. private struct Element
  38. {
  39. internal T Value;
  40. }
  41. /// <remarks>
  42. /// Not using System.Func{T} because this file is linked into the (debugger) Formatter,
  43. /// which does not have that type (since it compiles against .NET 2.0).
  44. /// </remarks>
  45. internal delegate T Factory();
  46. // Storage for the pool objects. The first item is stored in a dedicated field because we
  47. // expect to be able to satisfy most requests from it.
  48. private T _firstItem;
  49. private readonly Element[] _items;
  50. private int _currentSlowPooledItems;
  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. if (_currentSlowPooledItems <= 0)
  137. return CreateInstance();
  138. var items = _items;
  139. for (int i = 0; i < items.Length; i++)
  140. {
  141. T inst = items[i].Value;
  142. if (inst is not null)
  143. {
  144. _currentSlowPooledItems--;
  145. items[i].Value = null;
  146. return inst;
  147. }
  148. }
  149. return CreateInstance();
  150. }
  151. /// <summary>
  152. /// Returns objects to the pool.
  153. /// </summary>
  154. /// <remarks>
  155. /// Search strategy is a simple linear probing which is chosen for it cache-friendliness.
  156. /// Note that Free will try to store recycled objects close to the start thus statistically
  157. /// reducing how far we will typically search in Allocate.
  158. /// </remarks>
  159. internal void Free(T obj)
  160. {
  161. Validate(obj);
  162. ForgetTrackedObject(obj);
  163. if (_firstItem is null)
  164. {
  165. // Intentionally not using interlocked here.
  166. // In a worst case scenario two objects may be stored into same slot.
  167. // It is very unlikely to happen and will only mean that one of the objects will get collected.
  168. _firstItem = obj;
  169. }
  170. else
  171. {
  172. FreeSlow(obj);
  173. }
  174. }
  175. private void FreeSlow(T obj)
  176. {
  177. var items = _items;
  178. if (_currentSlowPooledItems >= items.Length)
  179. return;
  180. for (int i = 0; i < items.Length; i++)
  181. {
  182. if (ReferenceEquals(items[i].Value, null))
  183. {
  184. // Intentionally not using interlocked here.
  185. // In a worst case scenario two objects may be stored into same slot.
  186. // It is very unlikely to happen and will only mean that one of the objects will get collected.
  187. _currentSlowPooledItems++;
  188. items[i].Value = obj;
  189. break;
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// Removes an object from leak tracking.
  195. ///
  196. /// This is called when an object is returned to the pool. It may also be explicitly
  197. /// called if an object allocated from the pool is intentionally not being returned
  198. /// to the pool. This can be of use with pooled arrays if the consumer wants to
  199. /// return a larger array to the pool than was originally allocated.
  200. /// </summary>
  201. [Conditional("DEBUG")]
  202. internal void ForgetTrackedObject(T old, T replacement = null)
  203. {
  204. #if DETECT_LEAKS
  205. LeakTracker tracker;
  206. if (leakTrackers.TryGetValue(old, out tracker))
  207. {
  208. tracker.Dispose();
  209. leakTrackers.Remove(old);
  210. }
  211. else
  212. {
  213. var trace = CaptureStackTrace();
  214. Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nObject of type {typeof(T)} was freed, but was not from pool. \n Callstack: \n {trace} TRACEOBJECTPOOLLEAKS_END");
  215. }
  216. if (replacement != null)
  217. {
  218. tracker = new LeakTracker();
  219. leakTrackers.Add(replacement, tracker);
  220. }
  221. #endif
  222. }
  223. #if DETECT_LEAKS
  224. private static Lazy<Type> _stackTraceType = new Lazy<Type>(() => Type.GetType("System.Diagnostics.StackTrace"));
  225. private static object CaptureStackTrace()
  226. {
  227. return Activator.CreateInstance(_stackTraceType.Value);
  228. }
  229. #endif
  230. [Conditional("DEBUG")]
  231. private void Validate(object obj)
  232. {
  233. Debug.Assert(obj != null, "freeing null?");
  234. Debug.Assert(_firstItem != obj, "freeing twice?");
  235. var items = _items;
  236. for (int i = 0; i < items.Length; i++)
  237. {
  238. var value = items[i].Value;
  239. if (value is null)
  240. {
  241. return;
  242. }
  243. Debug.Assert(value != obj, "freeing twice?");
  244. }
  245. }
  246. }