ConcurrentObjectPool.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. using System.Threading;
  14. #if DETECT_LEAKS
  15. using System.Runtime.CompilerServices;
  16. #endif
  17. namespace Jint.Pooling;
  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 ConcurrentObjectPool<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 ConcurrentObjectPool(Factory factory)
  90. : this(factory, Environment.ProcessorCount * 2)
  91. { }
  92. internal ConcurrentObjectPool(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 == null || inst != Interlocked.CompareExchange(ref _firstItem, null, inst))
  119. {
  120. inst = AllocateSlow();
  121. }
  122. #if DETECT_LEAKS
  123. var tracker = new LeakTracker();
  124. leakTrackers.Add(inst, tracker);
  125. #if TRACE_LEAKS
  126. var frame = CaptureStackTrace();
  127. tracker.Trace = frame;
  128. #endif
  129. #endif
  130. return inst;
  131. }
  132. private T AllocateSlow()
  133. {
  134. var items = _items;
  135. for (int i = 0; i < items.Length; i++)
  136. {
  137. // Note that the initial read is optimistically not synchronized. That is intentional.
  138. // We will interlock only when we have a candidate. in a worst case we may miss some
  139. // recently returned objects. Not a big deal.
  140. T inst = items[i].Value;
  141. if (inst != null)
  142. {
  143. if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst))
  144. {
  145. return inst;
  146. }
  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 == 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. for (int i = 0; i < items.Length; i++)
  179. {
  180. if (items[i].Value == null)
  181. {
  182. // Intentionally not using interlocked here.
  183. // In a worst case scenario two objects may be stored into same slot.
  184. // It is very unlikely to happen and will only mean that one of the objects will get collected.
  185. items[i].Value = obj;
  186. break;
  187. }
  188. }
  189. }
  190. /// <summary>
  191. /// Removes an object from leak tracking.
  192. ///
  193. /// This is called when an object is returned to the pool. It may also be explicitly
  194. /// called if an object allocated from the pool is intentionally not being returned
  195. /// to the pool. This can be of use with pooled arrays if the consumer wants to
  196. /// return a larger array to the pool than was originally allocated.
  197. /// </summary>
  198. [Conditional("DEBUG")]
  199. internal void ForgetTrackedObject(T old, T replacement = null)
  200. {
  201. #if DETECT_LEAKS
  202. LeakTracker tracker;
  203. if (leakTrackers.TryGetValue(old, out tracker))
  204. {
  205. tracker.Dispose();
  206. leakTrackers.Remove(old);
  207. }
  208. else
  209. {
  210. var trace = CaptureStackTrace();
  211. Debug.WriteLine($"TRACEOBJECTPOOLLEAKS_BEGIN\nObject of type {typeof(T)} was freed, but was not from pool. \n Callstack: \n {trace} TRACEOBJECTPOOLLEAKS_END");
  212. }
  213. if (replacement != null)
  214. {
  215. tracker = new LeakTracker();
  216. leakTrackers.Add(replacement, tracker);
  217. }
  218. #endif
  219. }
  220. #if DETECT_LEAKS
  221. private static Lazy<Type> _stackTraceType = new Lazy<Type>(() => Type.GetType("System.Diagnostics.StackTrace"));
  222. private static object CaptureStackTrace()
  223. {
  224. return Activator.CreateInstance(_stackTraceType.Value);
  225. }
  226. #endif
  227. [Conditional("DEBUG")]
  228. private void Validate(object obj)
  229. {
  230. Debug.Assert(obj != null, "freeing null?");
  231. Debug.Assert(_firstItem != obj, "freeing twice?");
  232. var items = _items;
  233. for (int i = 0; i < items.Length; i++)
  234. {
  235. var value = items[i].Value;
  236. if (value == null)
  237. {
  238. return;
  239. }
  240. Debug.Assert(value != obj, "freeing twice?");
  241. }
  242. }
  243. }