DefaultObjectPool.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #region Copyright notice and license
  2. // Copyright 2017 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Threading;
  18. using System.Collections.Generic;
  19. using Grpc.Core.Utils;
  20. namespace Grpc.Core.Internal
  21. {
  22. /// <summary>
  23. /// Pool of objects that combines a shared pool and a thread local pool.
  24. /// </summary>
  25. internal class DefaultObjectPool<T> : IObjectPool<T>
  26. where T : class, IPooledObject<T>
  27. {
  28. readonly object myLock = new object();
  29. readonly Action<T> returnAction;
  30. readonly Func<T> itemFactory;
  31. // Queue shared between threads, access needs to be synchronized.
  32. readonly Queue<T> sharedQueue;
  33. readonly int sharedCapacity;
  34. readonly ThreadLocal<ThreadLocalData> threadLocalData;
  35. readonly int threadLocalCapacity;
  36. readonly int rentLimit;
  37. bool disposed;
  38. /// <summary>
  39. /// Initializes a new instance of <c>DefaultObjectPool</c> with given shared capacity and thread local capacity.
  40. /// Thread local capacity should be significantly smaller than the shared capacity as we don't guarantee immediately
  41. /// disposing the objects in the thread local pool after this pool is disposed (they will eventually be garbage collected
  42. /// after the thread that owns them has finished).
  43. /// On average, the shared pool will only be accessed approx. once for every <c>threadLocalCapacity / 2</c> rent or lease
  44. /// operations.
  45. /// </summary>
  46. public DefaultObjectPool(Func<T> itemFactory, int sharedCapacity, int threadLocalCapacity)
  47. {
  48. GrpcPreconditions.CheckArgument(sharedCapacity >= 0);
  49. GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0);
  50. this.returnAction = Return;
  51. this.itemFactory = GrpcPreconditions.CheckNotNull(itemFactory, nameof(itemFactory));
  52. this.sharedQueue = new Queue<T>(sharedCapacity);
  53. this.sharedCapacity = sharedCapacity;
  54. this.threadLocalData = new ThreadLocal<ThreadLocalData>(() => new ThreadLocalData(threadLocalCapacity), false);
  55. this.threadLocalCapacity = threadLocalCapacity;
  56. this.rentLimit = threadLocalCapacity != 1 ? threadLocalCapacity / 2 : 1;
  57. }
  58. /// <summary>
  59. /// Leases an item from the pool or creates a new instance if the pool is empty.
  60. /// Attempts to retrieve the item from the thread local pool first.
  61. /// If the thread local pool is empty, the item is taken from the shared pool
  62. /// along with more items that are moved to the thread local pool to avoid
  63. /// prevent acquiring the lock for shared pool too often.
  64. /// The methods should not be called after the pool is disposed, but it won't
  65. /// results in an error to do so (after depleting the items potentially left
  66. /// in the thread local pool, it will continue returning new objects created by the factory).
  67. /// </summary>
  68. public T Lease()
  69. {
  70. var item = LeaseInternal();
  71. item.SetReturnToPoolAction(returnAction);
  72. return item;
  73. }
  74. private T LeaseInternal()
  75. {
  76. var localData = threadLocalData.Value;
  77. if (localData.Queue.Count > 0)
  78. {
  79. return localData.Queue.Dequeue();
  80. }
  81. if (localData.CreateBudget > 0)
  82. {
  83. localData.CreateBudget --;
  84. return itemFactory();
  85. }
  86. int itemsMoved = 0;
  87. T leasedItem = null;
  88. lock(myLock)
  89. {
  90. if (sharedQueue.Count > 0)
  91. {
  92. leasedItem = sharedQueue.Dequeue();
  93. }
  94. while (sharedQueue.Count > 0 && itemsMoved < rentLimit)
  95. {
  96. localData.Queue.Enqueue(sharedQueue.Dequeue());
  97. itemsMoved ++;
  98. }
  99. }
  100. // If the shared pool didn't contain all rentLimit items,
  101. // next time we try to lease we will just create those
  102. // instead of trying to grab them from the shared queue.
  103. // This is to guarantee we won't be accessing the shared queue too often.
  104. localData.CreateBudget = rentLimit - itemsMoved;
  105. return leasedItem ?? itemFactory();
  106. }
  107. /// <summary>
  108. /// Returns an item to the pool.
  109. /// Attempts to add the item to the thread local pool first.
  110. /// If the thread local pool is full, item is added to a shared pool,
  111. /// along with half of the items for the thread local pool, which
  112. /// should prevent acquiring the lock for shared pool too often.
  113. /// If called after the pool is disposed, we make best effort not to
  114. /// add anything to the thread local pool and we guarantee not to add
  115. /// anything to the shared pool (items will be disposed instead).
  116. /// </summary>
  117. public void Return(T item)
  118. {
  119. GrpcPreconditions.CheckNotNull(item);
  120. var localData = threadLocalData.Value;
  121. if (localData.Queue.Count < threadLocalCapacity && !disposed)
  122. {
  123. localData.Queue.Enqueue(item);
  124. return;
  125. }
  126. if (localData.DisposeBudget > 0)
  127. {
  128. localData.DisposeBudget --;
  129. item.Dispose();
  130. return;
  131. }
  132. int itemsReturned = 0;
  133. int returnLimit = rentLimit + 1;
  134. lock (myLock)
  135. {
  136. if (sharedQueue.Count < sharedCapacity && !disposed)
  137. {
  138. sharedQueue.Enqueue(item);
  139. itemsReturned ++;
  140. }
  141. while (sharedQueue.Count < sharedCapacity && itemsReturned < returnLimit && !disposed)
  142. {
  143. sharedQueue.Enqueue(localData.Queue.Dequeue());
  144. itemsReturned ++;
  145. }
  146. }
  147. // If the shared pool could not accommodate all returnLimit items,
  148. // next time we try to return we will just dispose the item
  149. // instead of trying to return them to the shared queue.
  150. // This is to guarantee we won't be accessing the shared queue too often.
  151. localData.DisposeBudget = returnLimit - itemsReturned;
  152. if (itemsReturned == 0)
  153. {
  154. localData.DisposeBudget --;
  155. item.Dispose();
  156. }
  157. }
  158. public void Dispose()
  159. {
  160. lock (myLock)
  161. {
  162. if (!disposed)
  163. {
  164. disposed = true;
  165. while (sharedQueue.Count > 0)
  166. {
  167. sharedQueue.Dequeue().Dispose();
  168. }
  169. }
  170. }
  171. }
  172. class ThreadLocalData
  173. {
  174. public ThreadLocalData(int capacity)
  175. {
  176. this.Queue = new Queue<T>(capacity);
  177. }
  178. public Queue<T> Queue { get; }
  179. public int CreateBudget { get; set; }
  180. public int DisposeBudget { get; set; }
  181. }
  182. }
  183. }