I am using the Obervable-Observer Pattern.

MyClass extends Observable{

     notifyListeners();//This invokes onUpdate() in "implements Observer" 

     return value;

ClassTwo implements Observer{

      //This is called after notifyListeners();

My question is when will the onUpdate method in the Listener Class get invoked? After the invokeListeners() methods completes, or right after notifyListeners()?

  • With reference to the docs of Java 7, 8 and 9 - shouldn't it be notifyObservers() ? – Dev-iL Jun 16 '15 at 17:59
  • Please refer to Telastyn or Halter's answer. That is what I was looking for. – ARK Jun 16 '15 at 18:48

In the Implementation of

notifyListeners();//This invokes onUpdate() in "implements Observer"

is normally a loop over all registered Observers.

In this loop is normally a direct call to


on each registered Observer.

Be sure not to block the execution in the implementation of

  • So the method invokeListeners() is finished executing after all the update() methods in the observer are executed. – ARK Jun 16 '15 at 18:51

In general, notifyListeners is implemented as a list of delegates/observers which are just plain old functions that get called in order. So the observer functions will generally be invoked during the notifyListeners call (like your comment implies).

There are different possible implementations, some that run in parallel in background threads, some that send the request off to a queue, but the direct call is the most common.

  • Which is the most common implementation? Direct Call? And how is the order of listeners decided? – ARK Jun 16 '15 at 18:49
  • @akshayrajkore - yes direct call. Generally by order of addition to the event. – Telastyn Jun 16 '15 at 18:51
  • Thanks. I would have upvoted your answer, but I require 10 reputation. – ARK Jun 16 '15 at 18:52
  • 1
    @akshayrajkore Keep in mind though, that the listener order is implementation-dependent and not guaranteed. Depending on a particular order is probably a bad idea, the structure containing the listeners map be something like a tree or set, where no guarantees are made about traversal order. – Morgen Jun 16 '15 at 20:38

To check the stacktrace, I incremented a static int in the update() method of all the listeners.

I added a System.out.println() in the method where I call notifyListeners() and in the update() methods of the listeners to see the value of the static. Following is stacktrace values -

public static int observer = 0; //Initialized

StackTrace : After NotifyListeners : 0 In update() : 1 In update() : 2 In update() : 3

This implies that the method in which notifyListeners() call is placed, first completes its execution and after that the update() methods in the Observer are called in a loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.