namespace HeuristicLab.Problems.ProgramSynthesis.Push.Interpreter { using System; using System.Collections.Generic; using HeuristicLab.Problems.ProgramSynthesis.Push.Data.Pool; using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions; public class InterpreterPoolContainer { private readonly ManagedPoolProvider pushProgramPoolProvider; private readonly ManagedPoolProvider> expressionListPoolProvider; private readonly IDictionary> statefulExpressionPoolProviders = new Dictionary>(); private readonly IDictionary> statefulExpressionPools = new Dictionary>(); public InterpreterPoolContainer(int partitionSize = 512, int maxPartitionCount = 1024) { pushProgramPoolProvider = new ManagedPoolProvider(partitionSize, () => new PushProgram(), maxPartitionCount); expressionListPoolProvider = new ManagedPoolProvider>(partitionSize, () => new PooledList(), maxPartitionCount); InitStatefulExpressionPools(partitionSize, maxPartitionCount); } public InterpreterPoolContainer( ManagedPoolProvider pushProgramPoolProvider, ManagedPoolProvider> expressionListPoolProvider) { this.pushProgramPoolProvider = pushProgramPoolProvider; this.expressionListPoolProvider = expressionListPoolProvider; InitStatefulExpressionPools(1024, 2048); } private IManagedPool pushProgramPool; public IManagedPool PushProgramPool { get { if (pushProgramPool == null) pushProgramPool = pushProgramPoolProvider.CreatePool(); return pushProgramPool; } } private IManagedPool> expressionListPool; public IManagedPool> ExpressionListPool { get { if (expressionListPool == null) expressionListPool = expressionListPoolProvider.CreatePool(); return expressionListPool; } } private void InitStatefulExpressionPools(int partitionSize, int maxPartitionCount) { foreach (var type in ExpressionTable.StatefulExpressionTypes) { statefulExpressionPoolProviders.Add(type, new ManagedPoolProvider( partitionSize, ExpressionTable.StatefulExpressionFactory[type], maxPartitionCount)); statefulExpressionPools.Add(type, null); } } public T GetStatefulExpression() where T : Expression { var type = typeof(T); if (statefulExpressionPools[type] == null) statefulExpressionPools[type] = statefulExpressionPoolProviders[type].CreatePool(); return (T)statefulExpressionPools[type].Get(); } public IManagedPool GetStatefulExpressionPool() where T : Expression { var type = typeof(T); return statefulExpressionPools[type] ?? (statefulExpressionPools[type] = statefulExpressionPoolProviders[type].CreatePool()); } public void DisposePools() { if (pushProgramPool != null) { pushProgramPool.Dispose(); pushProgramPool = null; } if (expressionListPool != null) { expressionListPool.Dispose(); expressionListPool = null; } for (var i = 0; i < ExpressionTable.StatefulExpressionTypes.Count; i++) { var type = ExpressionTable.StatefulExpressionTypes[i]; var pool = statefulExpressionPools[type]; if (pool != null) { pool.Dispose(); statefulExpressionPools[type] = null; } } } } }