Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13069 was 13069, checked in by gkronber, 8 years ago

#2499: imported source code for HeuristicLab.BioBoost from private repository with some changes

File size: 1.4 KB
RevLine 
[13069]1using System;
2using System.Collections.Generic;
3
4namespace HeuristicLab.BioBoost.Evaluators {
5
6  /// <summary>
7  /// Object pool for reusing frequently created and discarded objects.
8  /// </summary>
9  /// <typeparam name="T"></typeparam>
10  public class ObjectPool<T> where T : new() {
11
12    private readonly Stack<T> pool;
13
14    public int MaxPoolSize { get; set; }
15
16    public Func<T> Create;
17    public Action<T> Clear;
18    public Func<T, int, bool> Accept;
19
20    private static void DoNothing(T o) {}
21    private static bool DefaultAccept(T o, int count) { return count < 100; }
22
23    public ObjectPool() : this(() => new T(), DoNothing, DefaultAccept) {}
24
25    public ObjectPool(Func<T> create, Action<T> clear, Func<T, int, bool> accept) {
26      pool = new Stack<T>();
27      Create = create;
28      Clear = clear;
29      Accept = accept;
30    }
31
32    public T Get() {
33      lock (this) {
34        if (pool.Count > 0) {
35          return pool.Pop();
36        }
37      }
38      return Create();
39    }
40
41    public T GetCleared() {
42      lock (this) {
43        if (pool.Count > 0) {
44          var val = pool.Pop();
45          Clear(val);
46          return val;
47        }
48      }
49      return Create();
50    }
51
52    public void Return(T o) {
53      lock (this) {
54        if (Accept(o, pool.Count))
55          pool.Push(o);
56      }
57    }
58
59    public void Reset() {
60      lock (this)
61        pool.Clear();
62    }
63
64  }
65}
Note: See TracBrowser for help on using the repository browser.