# HG changeset patch # User cin # Date 1419353327 -10800 # Node ID 8beee0d11de60de493d7e6d0eb570f260c28eab6 # Parent da56ba7b1aab57f94aec653b8ea6e6bea849ddd2 pool refactoring diff -r da56ba7b1aab -r 8beee0d11de6 Implab/DisposablePool.cs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Implab/DisposablePool.cs Tue Dec 23 19:48:47 2014 +0300 @@ -0,0 +1,90 @@ +using System; +using Implab.Parallels; +using System.Threading; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Implab { + public abstract class DisposablePool : IDisposable { + readonly int m_size; + readonly MTQueue m_queue = new MTQueue(); + + [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] + static readonly bool _isValueType = typeof(T).IsValueType; + + bool m_disposed; + + int m_count; + + protected DisposablePool(int size) { + m_size = size; + } + + protected DisposablePool() : this(Environment.ProcessorCount+1) { + } + + public T Allocate() { + if (m_disposed) + throw new ObjectDisposedException(ToString()); + + T instance; + if (m_queue.TryDequeue(out instance)) { + Interlocked.Decrement(ref m_count); + } else { + instance = CreateInstance(); + Debug.Assert(!Object.Equals(instance, default(T)) || _isValueType); + } + return instance; + } + + protected abstract T CreateInstance(); + + protected virtual void CleanupInstance(T instance) { + } + + public void Release(T instance) { + if ( Object.Equals(instance,default(T)) && !_isValueType) + return; + + Thread.MemoryBarrier(); + if (m_count < m_size && !m_disposed) { + Interlocked.Increment(ref m_count); + + CleanupInstance(instance); + + m_queue.Enqueue(instance); + + // пока элемент возвращался в кеш, была начата операция освобождения всего кеша + // и возможно уже законцена, в таком случае следует извлечь элемент обратно и + // освободить его. Если операция освобождения кеша еще не заврешилась, то будет + // изъят и освобожден произвольный элемен, что не повлияет на ход всего процесса. + if (m_disposed && m_queue.TryDequeue(out instance) && instance is IDisposable) + ((IDisposable)instance).Dispose() ; + + } else { + if (instance is IDisposable) + ((IDisposable)instance).Dispose(); + } + } + + protected virtual void Dispose(bool disposing) { + if (disposing) { + m_disposed = true; + T instance; + while (m_queue.TryDequeue(out instance)) + if (instance is IDisposable) + ((IDisposable)instance).Dispose(); + } + } + + #region IDisposable implementation + + public void Dispose() { + Dispose(true); + GC.SuppressFinalize(this); + } + + #endregion + } +} + diff -r da56ba7b1aab -r 8beee0d11de6 Implab/Implab.csproj --- a/Implab/Implab.csproj Tue Dec 23 03:20:39 2014 +0300 +++ b/Implab/Implab.csproj Tue Dec 23 19:48:47 2014 +0300 @@ -127,7 +127,6 @@ - @@ -139,7 +138,6 @@ - @@ -150,6 +148,8 @@ + + diff -r da56ba7b1aab -r 8beee0d11de6 Implab/ObjectPool.cs --- a/Implab/ObjectPool.cs Tue Dec 23 03:20:39 2014 +0300 +++ b/Implab/ObjectPool.cs Tue Dec 23 19:48:47 2014 +0300 @@ -1,90 +1,60 @@ -using System; -using Implab.Parallels; -using System.Threading; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; - -namespace Implab { - public abstract class ObjectPool : IDisposable { - readonly int m_size; - readonly MTQueue m_queue = new MTQueue(); - - [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] - static readonly bool _isValueType = typeof(T).IsValueType; - - bool m_disposed; - - int m_count; - - protected ObjectPool(int size) { - m_size = size; - } - - protected ObjectPool() : this(Environment.ProcessorCount+1) { - } - - public T Allocate() { - if (m_disposed) - throw new ObjectDisposedException(ToString()); - - T instance; - if (m_queue.TryDequeue(out instance)) { - Interlocked.Decrement(ref m_count); - } else { - instance = CreateInstance(); - Debug.Assert(!Object.Equals(instance, default(T)) || _isValueType); - } - return instance; - } - - protected abstract T CreateInstance(); - - protected virtual void CleanupInstance(T instance) { - } - - public void Release(T instance) { - if ( Object.Equals(instance,default(T)) && !_isValueType) - return; - - Thread.MemoryBarrier(); - if (m_count < m_size && !m_disposed) { - Interlocked.Increment(ref m_count); - - CleanupInstance(instance); - - m_queue.Enqueue(instance); - - // пока элемент возвращался в кеш, была начата операция освобождения всего кеша - // и возможно уже законцена, в таком случае следует извлечь элемент обратно и - // освободить его. Если операция освобождения кеша еще не заврешилась, то будет - // изъят и освобожден произвольный элемен, что не повлияет на ход всего процесса. - if (m_disposed && m_queue.TryDequeue(out instance) && instance is IDisposable) - ((IDisposable)instance).Dispose() ; - - } else { - if (instance is IDisposable) - ((IDisposable)instance).Dispose(); - } - } - - protected virtual void Dispose(bool disposing) { - if (disposing) { - m_disposed = true; - T instance; - while (m_queue.TryDequeue(out instance)) - if (instance is IDisposable) - ((IDisposable)instance).Dispose(); - } - } - - #region IDisposable implementation - - public void Dispose() { - Dispose(true); - GC.SuppressFinalize(this); - } - - #endregion - } -} - +using Implab.Parallels; +using System; +using System.Threading; + +namespace Implab { + /// + /// Базовый класс для создания пулов объектов. + /// + /// + /// Пул объектов позволяет многократно использовать один и тотже объект, + /// что актуально для объектов, создание которых требует существенных ресурсов. + /// Пул объектов использует слабые ссылки, чтобы не препятствовать освобождению + /// ресурсов и создает новые объекты при необходимости. + /// + /// Наследники должны реализовывать метод для создания + /// новых экземпляров. + /// + /// Пул поддерживает обращения сразу из нескольких потоков. + /// + public abstract class ObjectPool where T : class { + readonly MTQueue m_queue = new MTQueue(); + readonly int m_size; + int m_count = 0; + + protected ObjectPool() : this(Environment.ProcessorCount+1) { + + } + + protected ObjectPool(int size) { + Safe.ArgumentInRange(size,1,size,"size"); + + m_size = size; + } + + protected abstract T CreateInstance(); + + protected virtual void CleanupInstance(T instance) { + } + + public T Allocate() { + WeakReference reference; + while (m_queue.TryDequeue(out reference)) { + Interlocked.Decrement(ref m_count); + object instance = reference.Target; + if (instance == null) + continue; + return (T)instance; + } + return CreateInstance(); + } + + public void Release(T instance) { + if (m_count < m_size && instance != null) { + Interlocked.Increment(ref m_count); + CleanupInstance(instance); + m_queue.Enqueue(new WeakReference(instance)); + } + } + } +} diff -r da56ba7b1aab -r 8beee0d11de6 Implab/SafePool.cs --- a/Implab/SafePool.cs Tue Dec 23 03:20:39 2014 +0300 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,40 +0,0 @@ -using Implab.Parallels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; - -namespace Implab { - public class SafePool where T : new() { - readonly MTQueue m_queue = new MTQueue(); - readonly int m_size; - int m_count = 0; - - public SafePool() : this(10) { - - } - - public SafePool(int size) { - Safe.ArgumentInRange(size,1,size,"size"); - - m_size = size; - } - - public T Allocate() { - T instance; - if (m_queue.TryDequeue(out instance)) { - Interlocked.Decrement(ref m_count); - return instance; - } - return new T(); - } - - public void Release(T instance) { - if (m_count < m_size) { - Interlocked.Increment(ref m_count); - m_queue.Enqueue(instance); - } - } - } -} diff -r da56ba7b1aab -r 8beee0d11de6 Implab/ServiceLocator.cs --- a/Implab/ServiceLocator.cs Tue Dec 23 03:20:39 2014 +0300 +++ b/Implab/ServiceLocator.cs Tue Dec 23 19:48:47 2014 +0300 @@ -5,7 +5,7 @@ /// /// Коллекция сервисов, позволяет регистрировать и получать сервисы. /// - public class ServiceLocator: Component, IServiceLocator, IServiceProvider { + public class ServiceLocator: Disposable, IServiceLocator, IServiceProvider { // запись о сервисе struct ServiceEntry : IDisposable { public object service; // сервис