lundi 10 août 2015

Java: notifyObservers not concurrent?

I have 4 observers listening on an observable data. However one of my observer is slower and could take. I just saw the code of notifyObserver as:-

  132       public void notifyObservers(Object arg) {
  133           /*
  134            * a temporary array buffer, used as a snapshot of the state of
  135            * current Observers.
  136            */
  137           Object[] arrLocal;
  138   
  139           synchronized (this) {
/**comment removed for clarity **/

  152               if (!changed)
  153                   return;
  154               arrLocal = obs.toArray();
  155               clearChanged();
  156           }
  157   
  158           for (int i = arrLocal.length-1; i>=0; i--)
  159               ((Observer)arrLocal[i]).update(this, arg);
  160       }

From the code it is clear that the observers are called one after another. As by design observers are independent in execution. Shouldn't function be calling them in concurrently by making argas final?

curent time of execution is t1+t2+t3+t4 which should have been max(t1,t2,t3,t4). I could make update function of the observer non-blocking but that wouldn't be same and could cause some race condition as notifyObservers will exit without the observer being completely executed.

Am I missing something behind this design? Is it intentional and there is no way I could reduce the time here?

Aucun commentaire:

Enregistrer un commentaire