Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost/3.3/Evaluators/ObjectPool.cs @ 13071

Last change on this file since 13071 was 13071, checked in by gkronber, 9 years ago

#2499: added license headers and removed unused usings

File size: 2.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24
25namespace HeuristicLab.BioBoost.Evaluators {
26
27  /// <summary>
28  /// Object pool for reusing frequently created and discarded objects.
29  /// </summary>
30  /// <typeparam name="T"></typeparam>
31  public class ObjectPool<T> where T : new() {
32
33    private readonly Stack<T> pool;
34
35    public int MaxPoolSize { get; set; }
36
37    public Func<T> Create;
38    public Action<T> Clear;
39    public Func<T, int, bool> Accept;
40
41    private static void DoNothing(T o) {}
42    private static bool DefaultAccept(T o, int count) { return count < 100; }
43
44    public ObjectPool() : this(() => new T(), DoNothing, DefaultAccept) {}
45
46    public ObjectPool(Func<T> create, Action<T> clear, Func<T, int, bool> accept) {
47      pool = new Stack<T>();
48      Create = create;
49      Clear = clear;
50      Accept = accept;
51    }
52
53    public T Get() {
54      lock (this) {
55        if (pool.Count > 0) {
56          return pool.Pop();
57        }
58      }
59      return Create();
60    }
61
62    public T GetCleared() {
63      lock (this) {
64        if (pool.Count > 0) {
65          var val = pool.Pop();
66          Clear(val);
67          return val;
68        }
69      }
70      return Create();
71    }
72
73    public void Return(T o) {
74      lock (this) {
75        if (Accept(o, pool.Count))
76          pool.Push(o);
77      }
78    }
79
80    public void Reset() {
81      lock (this)
82        pool.Clear();
83    }
84
85  }
86}
Note: See TracBrowser for help on using the repository browser.