.NET Core 3.0之深入源码理解ObjectPool(二)

776次阅读  |  发布于4年以前

写在前面

前文主要介绍了ObjectPool的一些理论基础,本文主要从源码角度理解Microsoft.Extensions.ObjectPool是如何实现的。下图为其三大核心组件图:

核心组件

ObjectPool

ObjectPool是一个泛型抽象类,里面只有两个抽象方法,Get和Return。它从底层定义了最一般的接口。

源码如下:

public abstract class ObjectPool<T> where T : class
{
    /// <summary>
    /// Gets an object from the pool if one is available, otherwise creates one.
    /// </summary>
    /// <returns>A <typeparamref name="T"/>.</returns>
    public abstract T Get();

    /// <summary>
    /// Return an object to the pool.
    /// </summary>
    /// <param name="obj">The object to add to the pool.</param>
    public abstract void Return(T obj);
}

ObjectPoolProvider

ObjectPoolProvider也是抽象类,其内部内置了一个已经实现的Create泛型方法以及一个抽象Create方法,这代表两种ObjectPool的创建方式,一个是基于默认策略的,一个是基于用户自定义策略的。

public abstract class ObjectPoolProvider
{
    /// <summary>
    /// Creates an <see cref="ObjectPool"/>.
    /// </summary>
    /// <typeparam name="T">The type to create a pool for.</typeparam>
    public ObjectPool<T> Create<T>() where T : class, new()
    {
        return Create<T>(new DefaultPooledObjectPolicy<T>());
    }

    /// <summary>
    /// Creates an <see cref="ObjectPool"/> with the given <see cref="IPooledObjectPolicy{T}"/>.
    /// </summary>
    /// <typeparam name="T">The type to create a pool for.</typeparam>
    public abstract ObjectPool<T> Create<T>(IPooledObjectPolicy<T> policy) where T : class;
}

IPooledObjectPolicy

这个接口是一个泛型接口,用于提供一种策略来管理对象池中的对象,同样也有两个方法,Create和Return。

public interface IPooledObjectPolicy<T>
{
   /// <summary>
   /// Create a <typeparamref name="T"/>.
   /// </summary>
   /// <returns>The <typeparamref name="T"/> which was created.</returns>
   T Create();

   /// <summary>
  /// 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.
  /// </summary>
  /// <param name="obj">The object to return to the pool.</param>
  /// <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>
  bool Return(T obj);
}

该接口有一个实现PooledObjectPolicy,这是一个抽象类,内部有两个抽象方法:

public abstract class PooledObjectPolicy<T> : IPooledObjectPolicy<T>
{
    public abstract T Create();

    public abstract bool Return(T obj);
}

实现机制

其内部实现逻辑较为简单,充分考虑到了一般实现、对象追踪、对象释放等场景的使用方式。

以下为其逻辑图:

DefaultObjectPool

DefaultObjectPool实现了ObjectPool,其内部维护了一个结构体类型的私有数组,用于存储相关对象。该数组的大小在构造函数中定义,其实际大小为输入值减去1(默认情况下,其值为逻辑处理器数量的两倍)主要是因为DefaultObjectPool单独将首项定义了出来。

以下为DefaultObjectPool中Get和Return的实现:

public override T Get()
   {
       var item = _firstItem;
       if (item == null || Interlocked.CompareExchange(ref _firstItem, null, item) != item)
       {
           var items = _items;
           for (var i = 0; i < items.Length; i++)
           {
               item = items[i].Element;
              if (item != null && Interlocked.CompareExchange(ref items[i].Element, null, item) == item)
              {
                  return item;
              }
          }

          item = Create();
      }

      return item;
  }

  public override void Return(T obj)
  {
      if (_isDefaultPolicy || (_fastPolicy?.Return(obj) ?? _policy.Return(obj)))
      {
          if (_firstItem != null || Interlocked.CompareExchange(ref _firstItem, obj, null) != null)
          {
              var items = _items;
              for (var i = 0; i < items.Length && Interlocked.CompareExchange(ref items[i].Element, obj, null) != null; ++i)
              {
              }
          }
      }
  }

通过源码可以知道这两个方法大量使用了Interlocked.CompareExchange:

1:  public static int CompareExchange(

 2:      ref int location1,```
3:      int value,```

4: int comparand ```


5:  )```

比较location1与comparand,如果不相等,什么都不做;如果location1与comparand相等,则用value替换location1的值。无论比较结果相等与否,返回值都是location1中原有的值。

Interlocked.CompareExchange的使用确保了线程安全性。

DefaultObjectPoolProvider

DefaultObjectPoolProvider实现了ObjectPoolProvider,该类重写了Create方法并返回ObjectPool对象。该类还定义了MaximumRetained属性,默认情况下,其值为逻辑处理器数量的两倍。

其源码如下,比较简单:

public class DefaultObjectPoolProvider : ObjectPoolProvider
{
   /// <summary>
   /// The maximum number of objects to retain in the pool.
   /// </summary>
   public int MaximumRetained { get; set; } = Environment.ProcessorCount * 2;

   /// <inheritdoc/>
   public override ObjectPool<T> Create<T>(IPooledObjectPolicy<T> policy)
  {
      if (policy == null)
      {
          throw new ArgumentNullException(nameof(policy));
      }

      if (typeof(IDisposable).IsAssignableFrom(typeof(T)))
      {
          return new DisposableObjectPool<T>(policy, MaximumRetained);
      }

      return new DefaultObjectPool<T>(policy, MaximumRetained);
  }
}

其中DisposableObjectPool是DefaultObjectPool类的派生类,这个类也实现了IDisposable,用于创建可手动释放的ObjectPool对象。

其相关代码如下:

public void Dispose()
{
   _isDisposed = true;

   DisposeItem(_firstItem);
   _firstItem = null;

   ObjectWrapper[] items = _items;
   for (var i = 0; i < items.Length; i++)
  {
      DisposeItem(items[i].Element);
      items[i].Element = null;
  }
}

private void DisposeItem(T item)
{
  if (item is IDisposable disposable)
  {
      disposable.Dispose();
  }
}

DefaultPooledObjectPolicy

该类继承了PooledObjectPolicy,实现也非常简单。

不过值得注意的是,PooledObjectPolicy还有一个实现StringBuilderPooledObjectPolicy,这个类从命名上看就知道是基于StringBuilder的。其内部默认定义了StringBuilder的大小以及初始化容量。并确定了超出容量后,将不允许归还对象。

在我们自定义PooledObjectPolicy的时候,可以参考这段实现去扩展新的PooledObjectPolicy对象。

我们看一下源码:

public class StringBuilderPooledObjectPolicy : PooledObjectPolicy<StringBuilder>
{
   public int InitialCapacity { get; set; } = 100;

   public int MaximumRetainedCapacity { get; set; } = 4 * 1024;

   public override StringBuilder Create()
   {
       return new StringBuilder(InitialCapacity);
  }

  public override bool Return(StringBuilder obj)
  {
      if (obj.Capacity > MaximumRetainedCapacity)
      {
          // Too big. Discard this one.
          return false;
      }

      obj.Clear();
      return true;
  }
}

对象追踪

该库内部定义了LeakTrackingObjectPool和LeakTrackingObjectPoolProvider用于追踪对象状态。

Tracker是LeakTrackingObjectPool的内部类,其目的是为了方便我们对对象本身进行维护跟踪,其定义如下:

private class Tracker : IDisposable
{
    private readonly string _stack;
    private bool _disposed;

    public Tracker()
    {
        _stack = Environment.StackTrace;
    }

    public void Dispose()
    {
        _disposed = true;
        GC.SuppressFinalize(this);
    }

    ~Tracker()
    {
        if (!_disposed && !Environment.HasShutdownStarted)
        {
            Debug.Fail($"{typeof(T).Name} was leaked. Created at: {Environment.NewLine}{_stack}");
        }
    }
}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8