First commit
[anna.git] / include / anna / core / mt / SafeRecycler.hpp
1 // ANNA - Anna is Not 'N' Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_core_mt_SafeRecycler_hpp
38 #define anna_core_mt_SafeRecycler_hpp
39
40 #include <stack>
41 #include <vector>
42 #include <algorithm>
43 #include <typeinfo>
44
45 #include <anna/core/RuntimeException.hpp>
46 #include <anna/core/mt/Mutex.hpp>
47 #include <anna/core/Allocator.hpp>
48 #include <anna/core/mt/Guard.hpp>
49 #include <anna/core/util/Recycler.hpp>
50
51 namespace anna {
52
53 /**
54    Mantiene una lista de punteros que puede crecer dinamicamente, no obstante, siempre que sea posible
55    intenta reusar punteros creados previamente.
56
57    Establece secciones critidas para acceder a los datos.
58
59    @param T Clase de la que mantener la lista de punteros pre-asignados.
60    @param Allocator Clase encargada de reservar la memoria para los objetos T en el momento en que sea necesaria
61    una nueva instancia.
62 */
63 template < typename T, typename _Allocator = Allocator <T> >
64 class SafeRecycler : public Recycler <T, _Allocator>, public Mutex {
65 public:
66   typedef typename Recycler <T, _Allocator>::iterator iterator;
67   typedef typename Recycler <T, _Allocator>::const_iterator const_iterator;
68
69   /**
70      Constructor.
71      \param randomAccess Indicador que permite activar el uso de estructuras de datos adicionales
72      Se ha comprobado que si necesitamos tratar en torno a un centenar de instancias
73      es más eficiente no activar las estructuras para acceso directo, para más objetos resulta
74      imprescinble.
75   */
76   SafeRecycler(const bool randomAccess = false) : Recycler <T, _Allocator> (randomAccess)  {;}
77
78   /**
79      Destructor.
80   */
81   virtual ~SafeRecycler() { ; }
82
83   /**
84      Devuelve un puntero de tipo T. Solo crearia una nueva instancia de la clase T si al invocar a este
85      metoodo no existe ninguna otra instancia que se pueda reutilizar, en cuyo caso haria una nueva reserva.
86
87      Cada una de las llamadas a este metodo debe tener su correspondiente llamada al metodo  #release cuando
88      el puntero deje de ser util.
89
90      @return Un puntero a una instancia de tipo T.
91   */
92   T* create()
93   throw(RuntimeException) {
94     std::string name(typeid(*this).name());
95     name += "::create";
96     Guard guard(this, name.c_str());
97     return Recycler <T, _Allocator>::create();
98   }
99
100   /**
101      Devuelve el iterador que apunta al objeto recibido como parametro.
102      \return el iterador que apunta al objeto recibido como parametro.
103   */
104   iterator find(T* t)
105   throw(RuntimeException) {
106     std::string name(typeid(*this).name());
107     name += "::find";
108     Guard guard(this, name.c_str());
109     return Recycler <T, _Allocator>::find(t);
110   }
111
112   /**
113      Libera el puntero recibido como parametro. No se libera fisicamente sino que se deja marcado como
114      reusable.
115
116      Si el puntero pasado como parametro no ha sido obtenido mediante el metodo #create los resultados
117      no estan definidos.
118
119      @param t Instancia de un puntero de tipo T obtenido a partir del metodo #create.
120   */
121   void release(T* t)
122   throw() {
123     if(t == NULL)
124       return;
125
126     try {
127       std::string name(typeid(*this).name());
128       name += "::release (T*)";
129       Guard guard(this, name.c_str());
130       Recycler <T, _Allocator>::release(t);
131     } catch(Exception& ex) {
132       ex.trace();
133     }
134   }
135
136   /**
137      Libera el puntero asociado al iterador recibido como parametro.
138      \param ii Instancia a liberar.
139   */
140   void release(iterator& ii) throw() {
141     try {
142       std::string name(typeid(*this).name());
143       name += "::release (iterator)";
144       Guard guard(this, name.c_str());
145       Recycler <T, _Allocator>::release(ii);
146     } catch(Exception& ex) {
147       ex.trace();
148     }
149   }
150
151   /**
152      Libera el puntero recibido como parametro. No se libera fisicamente sino que se deja marcado como
153      reusable.
154
155      Si el puntero pasado como parametro no ha sido obtenido mediante el metodo #create los resultados
156      no estan definidos.
157
158      @param t Instancia de un puntero de tipo T obtenido a partir del metodo #create.
159   */
160   void release(const T* t) throw() { release(const_cast <T*>(t)); }
161
162   /**
163      Marca como disponibles todos los objetos contenidos en memoria.
164   */
165   void clear()
166   throw() {
167     std::string name(typeid(*this).name());
168     name += "::clear";
169     Guard guard(this, name.c_str());
170     Recycler <T, _Allocator>::clear();
171   }
172 };
173
174 }
175
176 #endif
177