source: src/Observer/Observable.cpp@ 44f368

Last change on this file since 44f368 was b324a3, checked in by Frederik Heber <heber@…>, 12 years ago

Added Graveyard for to-be-destroyed Observables.

  • also added Zombie class that wraps an Observable.
  • Notification and Observable have new function getNumberOfObservers().
  • added unit test for Graveyard.
  • Property mode set to 100644
File size: 13.6 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * Observable.cpp
10 *
11 * Created on: Dec 1, 2011
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "CodePatterns/MemDebug.hpp"
21
22#include "CodePatterns/Observer/Observable.hpp"
23
24#include "CodePatterns/Assert.hpp"
25#include "CodePatterns/Observer/Channels.hpp"
26#include "CodePatterns/Observer/defs.hpp"
27#include "CodePatterns/Observer/Notification.hpp"
28
29//!> This function does nothing with the given Observable
30void NoOp_informer(const Observable *)
31{}
32
33Observable::graveyard_informer_t Observable::noop_informer(&NoOp_informer);
34
35// All infrastructure for the observer-pattern is bundled at a central place
36// this is more efficient if many objects can be observed (inherit from observable)
37// but only few are actually coupled with observers. E.g. TMV has over 500.000 Atoms,
38// which might become observable. Handling Observable infrastructure in each of
39// these would use memory for each atom. By handling Observer-infrastructure
40// here we only need memory for objects that actually are observed.
41// See [Gamma et al, 1995] p. 297
42
43std::map<Observable*, int> Observable::depth; //!< Map of Observables to the depth of the DAG of Observers
44std::map<Observable*,std::multimap<int,Observer*> > Observable::callTable; //!< Table for each Observable of all its Observers
45std::map<Observable*,std::set<Notification*> > Observable::notifications; //!< Table for all current notifications to perform
46std::set<Observable*> Observable::busyObservables; //!< Set of Observables that are currently busy notifying their sign-on'ed Observers
47Observable::ChannelMap Observable::NotificationChannels; //!< Map of Observables to their Channels.
48
49// ValidRange must be initialized before PriorityLevel.
50range<int> Observable::PriorityLevel::ValidRange(-20, 21);
51Observable::PriorityLevel Observable::PriorityDefault(int(0));
52
53/** Constructor of PriorityLevel.
54 *
55 * \note We check whether the level is within Observable::PriorityLevel::ValidRange.
56 *
57 * @param i priority level encapsulated in this class.
58 */
59Observable::PriorityLevel::PriorityLevel(const int i) :
60 level(i)
61{
62 ASSERT(ValidRange.isInRange(level),
63 "Observable::PriorityLevel::PriorityLevel() - Priority level "
64 +toString(level)+" out of range "+toString(ValidRange)+".");
65}
66
67Observable::PriorityLevel::~PriorityLevel()
68{}
69
70/** Attaching Sub-observables to Observables.
71 * Increases entry in Observable::depth for this \a *publisher by one.
72 *
73 * The two functions \sa start_observer_internal() and \sa finish_observer_internal()
74 * have to be used together at all time. Never use these functions directly
75 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
76 * thus producing compiler-errors whenever only one is used.
77 * \param *publisher reference of sub-observable
78 */
79void Observable::start_observer_internal(Observable *publisher){
80 // increase the count for this observable by one
81 // if no entry for this observable is found, an new one is created
82 // by the STL and initialized to 0 (see STL documentation)
83#ifdef LOG_OBSERVER
84 observerLog().addMessage(depth[publisher]) << ">> Locking " << observerLog().getName(publisher);
85#endif
86 depth[publisher]++;
87}
88
89/** Detaching Sub-observables from Observables.
90 * Decreases entry in Observable::depth for this \a *publisher by one. If zero, we
91 * start notifying all our Observers.
92 *
93 * The two functions start_observer_internal() and finish_observer_internal()
94 * have to be used together at all time. Never use these functions directly
95 * START_OBSERVER and FINISH_OBSERVER also construct a bogus while(0) loop
96 * thus producing compiler-errors whenever only one is used.
97 * \param *publisher reference of sub-observable
98 */
99void Observable::finish_observer_internal(Observable *publisher){
100 // decrease the count for this observable
101 // if zero is reached all observed blocks are done and we can
102 // start to notify our observers
103 --depth[publisher];
104#ifdef LOG_OBSERVER
105 observerLog().addMessage(depth[publisher]) << "<< Unlocking " << observerLog().getName(publisher);
106#endif
107 if(depth[publisher]){}
108 else{
109 publisher->notifyAll();
110 // this item is done, so we don't have to keep the count with us
111 // save some memory by erasing it
112 depth.erase(publisher);
113 }
114}
115
116void Observable::enque_notification_internal(Observable *publisher, Notification_ptr notification){
117 notifications[publisher].insert(notification);
118}
119
120/** Constructor for Observable Protector.
121 * Basically, calls start_observer_internal(). Hence use this class instead of
122 * calling the function directly.
123 *
124 * \param *protege Observable to be protected.
125 */
126Observable::_Observable_protector::_Observable_protector(Observable *_protege) :
127 protege(_protege)
128{
129 start_observer_internal(protege);
130}
131
132Observable::_Observable_protector::_Observable_protector(const _Observable_protector &dest) :
133 protege(dest.protege)
134{
135 start_observer_internal(protege);
136}
137
138/** Destructor for Observable Protector.
139 * Basically, calls finish_observer_internal(). Hence use this class instead of
140 * calling the function directly.
141 *
142 * \param *protege Observable to be protected.
143 */
144Observable::_Observable_protector::~_Observable_protector()
145{
146 finish_observer_internal(protege);
147}
148
149/************* Notification mechanism for observables **************/
150
151/** Notify all Observers of changes.
152 * Puts \a *this into Observable::busyObservables, calls Observer::update() for all in callee_t
153 * and removes from busy list.
154 */
155void Observable::notifyAll() {
156 // we are busy notifying others right now
157 // add ourselves to the list of busy subjects to enable circle detection
158 busyObservables.insert(this);
159 // see if anyone has signed up for observation
160 // and call all observers
161 try {
162 if(callTable.count(this)) {
163 // elements are stored sorted by keys in the multimap
164 // so iterating over it gives us a the callees sorted by
165 // the priorities
166 callees_t callees = callTable[this];
167 callees_t::iterator iter;
168 for(iter=callees.begin();iter!=callees.end();++iter){
169#ifdef LOG_OBSERVER
170 observerLog().addMessage() << "-> Sending update from " << observerLog().getName(this)
171 << " to " << observerLog().getName((*iter).second)
172 << " (priority=" << (*iter).first << ")";
173#endif
174 (*iter).second->update(this);
175 }
176 }
177 }
178 ASSERT_NOCATCH("Exception thrown from Observer Update");
179
180 // send out all notifications that need to be done
181
182 notificationSet currentNotifications = notifications[this];
183 for(notificationSet::iterator it = currentNotifications.begin();
184 it != currentNotifications.end();++it){
185 (*it)->notifyAll(this);
186 }
187
188 notifications.erase(this);
189
190 // done with notification, we can leave the set of busy subjects
191 busyObservables.erase(this);
192}
193
194
195/** Handles passing on updates from sub-Observables.
196 * Mimicks basically the Observer::update() function.
197 *
198 * \param *publisher The \a *this we observe.
199 */
200void Observable::update(Observable *publisher) {
201 // circle detection
202 if(busyObservables.find(this)!=busyObservables.end()) {
203 // somehow a circle was introduced... we were busy notifying our
204 // observers, but still we are called by one of our sub-Observables
205 // we cannot be sure observation will still work at this point
206 ASSERT(0,"Circle detected in observation-graph.\n"
207 "Observation-graph always needs to be a DAG to work correctly!\n"
208 "Please check your observation code and fix this!\n");
209 return;
210 }
211 else {
212 // see if we are in the process of changing ourselves
213 // if we are changing ourselves at the same time our sub-observables change
214 // we do not need to publish all the changes at each time we are called
215 if(depth.find(this)==depth.end()) {
216#ifdef LOG_OBSERVER
217 observerLog().addMessage() << "-* Update from " << observerLog().getName(publisher)
218 << " propagated by " << observerLog().getName(this);
219#endif
220 notifyAll();
221 }
222 else{
223#ifdef LOG_OBSERVER
224 observerLog().addMessage() << "-| Update from " << observerLog().getName(publisher)
225 << " not propagated by " << observerLog().getName(this);
226#endif
227 }
228 }
229}
230
231/** Sign on an Observer to this Observable.
232 * Puts \a *target into Observable::callTable list.
233 * \param *target Observer
234 * \param priority number in [-20,20]
235 */
236void Observable::signOn(Observer *target, PriorityLevel priority) const
237{
238#ifdef LOG_OBSERVER
239 observerLog().addMessage() << "@@ Signing on " << observerLog().getName(target) << " to " << observerLog().getName(const_cast<Observable *>(this));
240#endif
241 bool res = false;
242 callees_t &callees = callTable[const_cast<Observable *>(this)];
243
244 callees_t::iterator iter;
245 for(iter=callees.begin();iter!=callees.end();++iter){
246 res |= ((*iter).second == target);
247 }
248 if(!res)
249 callees.insert(std::pair<int,Observer*>(priority.level,target));
250}
251
252/** Sign off an Observer from this Observable.
253 * Removes \a *target from Observable::callTable list.
254 * \param *target Observer
255 */
256void Observable::signOff(Observer *target) const
257{
258 ASSERT(callTable.count(const_cast<Observable *>(this)),
259 "SignOff called for an Observable without Observers.");
260#ifdef LOG_OBSERVER
261 observerLog().addMessage() << "** Signing off " << observerLog().getName(target) << " from " << observerLog().getName(const_cast<Observable *>(this));
262#endif
263 callees_t &callees = callTable[const_cast<Observable *>(this)];
264
265 callees_t::iterator iter;
266 callees_t::iterator deliter;
267 for(iter=callees.begin();iter!=callees.end();) {
268 if((*iter).second == target) {
269 callees.erase(iter++);
270 }
271 else {
272 ++iter;
273 }
274 }
275 if(callees.empty()){
276 callTable.erase(const_cast<Observable *>(this));
277 }
278 graveyard_informer(this);
279}
280
281void Observable::signOn(Observer *target, size_t channelno) const
282{
283 Notification_ptr notification = getChannel(channelno);
284#ifdef LOG_OBSERVER
285 observerLog().addMessage() << "@@ Signing on " << observerLog().getName(target)
286 << " to " << observerLog().getName(const_cast<Observable *>(this))
287 << "'s channel no." << channelno << ".";
288#endif
289 notification->addObserver(target);
290}
291
292void Observable::signOff(Observer *target, size_t channelno) const
293{
294 Notification_ptr notification = getChannel(channelno);
295#ifdef LOG_OBSERVER
296 observerLog().addMessage() << "** Signing off " << observerLog().getName(target)
297 << " from " << observerLog().getName(const_cast<Observable *>(this))
298 << "'s channel no." << channelno << ".";
299#endif
300 notification->removeObserver(target);
301 graveyard_informer(this);
302}
303
304bool Observable::isBlocked() const
305{
306 return depth.count(const_cast<Observable *>(this)) > 0;
307}
308
309Notification_ptr Observable::getChannel(size_t no) const
310{
311 const ChannelMap::const_iterator iter = NotificationChannels.find(const_cast<Observable * const>(this));
312 ASSERT(iter != NotificationChannels.end(),
313 "Observable::getChannel() - we do not have a channel in NotificationChannels.");
314 const Channels *OurChannel = iter->second;
315 ASSERT(OurChannel != NULL,
316 "Observable::getChannel() - observable has no channels.");
317 return OurChannel->getChannel(no);
318}
319
320size_t Observable::getNumberOfObservers() const
321{
322 size_t ObserverCount = 0;
323 {
324 std::map<Observable*,callees_t>::const_iterator callTableiter =
325 callTable.find(const_cast<Observable *>(this));
326 // if not present, then we have zero observers
327 if (callTableiter != callTable.end())
328 ObserverCount += callTableiter->second.size();
329 }
330 {
331 const ChannelMap::const_iterator iter =
332 NotificationChannels.find(const_cast<Observable * const>(this));
333 // if not present, then we have zero observers
334 if (iter != NotificationChannels.end())
335 for (Channels::NotificationTypetoRefMap::const_iterator channeliter = iter->second->ChannelMap.begin();
336 channeliter != iter->second->ChannelMap.end();
337 ++channeliter)
338 ObserverCount += (channeliter->second)->getNumberOfObservers();
339 }
340 return ObserverCount;
341}
342
343/** Handles sub-observables that just got killed
344 * when an sub-observerable dies we usually don't need to do anything
345 * \param *publisher Sub-Observable.
346 */
347void Observable::subjectKilled(Observable *publisher){
348}
349
350/** Constructor for class Observable.
351 */
352Observable::Observable(std::string name) :
353 Observer(Observer::BaseConstructor()),
354 graveyard_informer(noop_informer)
355{
356#ifdef LOG_OBSERVER
357 observerLog().addName(this,name);
358 observerLog().addMessage() << "++ Creating Observable "
359 << observerLog().getName(static_cast<Observable *>(this));
360#endif
361}
362
363/** Destructor for class Observable.
364 * When an observable is deleted, we let all our observers know. \sa Observable::subjectKilled().
365 */
366Observable::~Observable()
367{
368#ifdef LOG_OBSERVER
369 observerLog().addMessage() << "-- Destroying Observable "
370 << observerLog().getName(static_cast<Observable *>(this));
371#endif
372 if(callTable.count(this)) {
373 // delete all entries for this observable
374 callees_t callees = callTable[this];
375 callees_t::iterator iter;
376 for(iter=callees.begin();iter!=callees.end();++iter)
377 (*iter).second->subjectKilled(this);
378 callTable.erase(this);
379 }
380
381 // also kill instance in static Channels map if present
382 ChannelMap::iterator iter = NotificationChannels.find(static_cast<Observable *>(this));
383 if (iter != NotificationChannels.end()) {
384 iter->second->subjectKilled(static_cast<Observable *>(this));
385 delete iter->second;
386 NotificationChannels.erase(iter);
387 }
388}
Note: See TracBrowser for help on using the repository browser.