写在前面
前文主要介绍了ObjectPool的一些理论基础,本文主要从源码角度理解Microsoft.Extensions.ObjectPool是如何实现的。下图为其三大核心组件图:
核心组件
ObjectPool
ObjectPool是一个泛型抽象类,里面只有两个抽象方法,Get和Return。它从底层定义了最一般的接口。
- Get方法用于从对象池获取到可用对象,如果对象不可用则创建对象并返回出来
- Return方法用户将对象返回到对象池
源码如下:
1: public abstract class ObjectPool<T> where T : class
2: {
3: /// <summary>
4: /// Gets an object from the pool if one is available, otherwise creates one.
5: /// </summary>
6: /// <returns>A <typeparamref name="T"/>.</returns>
7: public abstract T Get();
8:
9: /// <summary>
10: /// Return an object to the pool.
11: /// </summary>
12: /// <param name="obj">The object to add to the pool.</param>
13: public abstract void Return(T obj);
14: }
ObjectPoolProvider
ObjectPoolProvider也是抽象类,其内部内置了一个已经实现的Create泛型方法以及一个抽象Create方法,这代表两种ObjectPool的创建方式,一个是基于默认策略的,一个是基于用户自定义策略的。
1: public abstract class ObjectPoolProvider
2: {
3: /// <summary>
4: /// Creates an <see cref="ObjectPool"/>.
5: /// </summary>
6: /// <typeparam name="T">The type to create a pool for.</typeparam>
7: public ObjectPool<T> Create<T>() where T : class, new()
8: {
9: return Create<T>(new DefaultPooledObjectPolicy<T>());
10: }
11:
12: /// <summary>
13: /// Creates an <see cref="ObjectPool"/> with the given <see cref="IPooledObjectPolicy{T}"/>.
14: /// </summary>
15: /// <typeparam name="T">The type to create a pool for.</typeparam>
16: public abstract ObjectPool<T> Create<T>(IPooledObjectPolicy<T> policy) where T : class;
17: }
IPooledObjectPolicy
这个接口是一个泛型接口,用于提供一种策略来管理对象池中的对象,同样也有两个方法,Create和Return。
- Create方法用于创建相关类型实例
- Return方法用于将已经使用好的对象放回到对象池的时候进行逻辑处理,包括对象的状态重置以及是否能够放回到对象池
1: public interface IPooledObjectPolicy<T>
2: {
3: /// <summary>
4: /// Create a <typeparamref name="T"/>.
5: /// </summary>
6: /// <returns>The <typeparamref name="T"/> which was created.</returns>
7: T Create();
8:
9: /// <summary>
10: /// Runs some processing when an object was returned to the pool. Can be used to reset the state of an object and indicate if the object should be returned to the pool.
11: /// </summary>
12: /// <param name="obj">The object to return to the pool.</param>
13: /// <returns><code>true</code> if the object should be returned to the pool. <code>false</code> if it's not possible/desirable for the pool to keep the object.</returns>
14: bool Return(T obj);
15: }
该接口有一个实现PooledObjectPolicy,这是一个抽象类,内部有两个抽象方法:
1: public abstract class PooledObjectPolicy<T> : IPooledObjectPolicy<T>
2: {
3: public abstract T Create();
4:
5: public abstract bool Return(T obj);
6: }
实现机制
其内部实现逻辑较为简单,充分考虑到了一般实现、对象追踪、对象释放等场景的使用方式。
DefaultObjectPool
DefaultObjectPool实现了ObjectPool,其内部维护了一个结构体类型的私有数组,用于存储相关对象。该数组的大小在构造函数中定义,其实际大小为输入值减去1(默认情况下,其值为逻辑处理器数量的两倍)主要是因为DefaultObjectPool单独将首项定义了出来。
以下为DefaultObjectPool中Get和Return的实现:
1: public override T Get()
2: {
3: var item = _firstItem;
4: if (item == null || Interlocked.CompareExchange(ref _firstItem, null, item) != item)
5: {
6: var items = _items;
7: for (var i = 0; i < items.Length; i++)
8: {
9: item = items[i].Element;
10: if (item != null && Interlocked.CompareExchange(ref items[i].Element, null, item) == item)
11: {
12: return item;
13: }
14: }
15:
16: item = Create();
17: }
18:
19: return item;
20: }
21:
22: public override void Return(T obj)
23: {
24: if (_isDefaultPolicy || (_fastPolicy?.Return(obj) ?? _policy.Return(obj)))
25: {
26: if (_firstItem != null || Interlocked.CompareExchange(ref _firstItem, obj, null) != null)
27: {
28: var items = _items;
29: for (var i = 0; i < items.Length && Interlocked.CompareExchange(ref items[i].Element, obj, null) != null; ++i)
30: {
31: }
32: }
33: }
34: }
通过源码可以知道这两个方法大量使用了Interlocked.CompareExchange:
1: public static int CompareExchange(2: ref int location1,3: int value,4: int comparand5: )
比较location1与comparand,如果不相等,什么都不做;如果location1与comparand相等,则用value替换location1的值。无论比较结果相等与否,返回值都是location1中原有的值。
Interlocked.CompareExchange的使用确保了线程安全性。
DefaultObjectPoolProvider
DefaultObjectPoolProvider实现了ObjectPoolProvider,该类重写了Create方法并返回ObjectPool对象。该类还定义了MaximumRetained属性,默认情况下,其值为逻辑处理器数量的两倍。
其源码如下,比较简单:
1: public class DefaultObjectPoolProvider : ObjectPoolProvider
2: {
3: /// <summary>
4: /// The maximum number of objects to retain in the pool.
5: /// </summary>
6: public int MaximumRetained { get; set; } = Environment.ProcessorCount * 2;
7:
8: /// <inheritdoc/>
9: public override ObjectPool<T> Create<T>(IPooledObjectPolicy<T> policy)
10: {
11: if (policy == null)
12: {
13: throw new ArgumentNullException(nameof(policy));
14: }
15:
16: if (typeof(IDisposable).IsAssignableFrom(typeof(T)))
17: {
18: return new DisposableObjectPool<T>(policy, MaximumRetained);
19: }
20:
21: return new DefaultObjectPool<T>(policy, MaximumRetained);
22: }
23: }
其中DisposableObjectPool是DefaultObjectPool类的派生类,这个类也实现了IDisposable,用于创建可手动释放的ObjectPool对象。
其相关代码如下:
1: public void Dispose()
2: {
3: _isDisposed = true;
4:
5: DisposeItem(_firstItem);
6: _firstItem = null;
7:
8: ObjectWrapper[] items = _items;
9: for (var i = 0; i < items.Length; i++)
10: {
11: DisposeItem(items[i].Element);
12: items[i].Element = null;
13: }
14: }
15:
16: private void DisposeItem(T item)
17: {
18: if (item is IDisposable disposable)
19: {
20: disposable.Dispose();
21: }
22: }
DefaultPooledObjectPolicy
该类继承了PooledObjectPolicy,实现也非常简单。
不过值得注意的是,PooledObjectPolicy还有一个实现StringBuilderPooledObjectPolicy,这个类从命名上看就知道是基于StringBuilder的。其内部默认定义了StringBuilder的大小以及初始化容量。并确定了超出容量后,将不允许归还对象。
在我们自定义PooledObjectPolicy的时候,可以参考这段实现去扩展新的PooledObjectPolicy对象。
我们看一下源码:
1: public class StringBuilderPooledObjectPolicy : PooledObjectPolicy<StringBuilder>
2: {
3: public int InitialCapacity { get; set; } = 100;
4:
5: public int MaximumRetainedCapacity { get; set; } = 4 * 1024;
6:
7: public override StringBuilder Create()
8: {
9: return new StringBuilder(InitialCapacity);
10: }
11:
12: public override bool Return(StringBuilder obj)
13: {
14: if (obj.Capacity > MaximumRetainedCapacity)
15: {
16: // Too big. Discard this one.
17: return false;
18: }
19:
20: obj.Clear();
21: return true;
22: }
23: }
对象追踪
该库内部定义了LeakTrackingObjectPool和LeakTrackingObjectPoolProvider用于追踪对象状态。
- LeakTrackingObjectPoolProvider会根据构造函数传入的ObjectPoolProvider类型对象,创建LeakTrackingObjectPool实例。
- LeakTrackingObjectPool内部定义了ConditionalWeakTable<T, Tracker>类型的数组,MSDN的解释是使编译器可以将对象字段动态附加到托管对象,这个对象会自动维护内部的键值对,而不会一直使其停留在内存中。
Tracker是LeakTrackingObjectPool的内部类,其目的是为了方便我们对对象本身进行维护跟踪,其定义如下:
1: private class Tracker : IDisposable
2: {
3: private readonly string _stack;
4: private bool _disposed;
5:
6: public Tracker()
7: {
8: _stack = Environment.StackTrace;
9: }
10:
11: public void Dispose()
12: {
13: _disposed = true;
14: GC.SuppressFinalize(this);
15: }
16:
17: ~Tracker()
18: {
19: if (!_disposed && !Environment.HasShutdownStarted)
20: {
21: Debug.Fail($"{typeof(T).Name} was leaked. Created at: {Environment.NewLine}{_stack}");
22: }
23: }
24: }