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