Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid infinite loop in Observer pattern?

I have only one class with many instances. Every instance is observer of couple of other instances. As well every instance can be observable by couple of another instances.

How to avoid infinite loop of calling update() in observers?

like image 958
joseph Avatar asked Mar 17 '10 17:03

joseph


1 Answers

If your system is single threaded, then you simply need a guard inside your notify method:

private boolean _notifying;

public void notify() {
  if(_notifying) {
    return;
  }
  _notifying = true;
  try {
    // ... do notifying here...
  } finally {
    _notifying = false;
  }
}
like image 70
james Avatar answered Sep 30 '22 20:09

james