Search code examples
javaobserver-pattern

Java behavior of Observer class on being notified multiple times


I wanted to know what happens when an Observer is notified multiple times while it's still executing overridden method update(Observable observable, Object obj).

I have a concrete Observable class:

public class HttpRequestQueue extends Observable{

//an example queue(for explanation) and other class members
public Queue queue..

public void addToQueue(HttpRequest request){
    queue.add(request);
    setChanged();
    notifyObservers();
}

}

Another class which is the Observer

public class Webclient implements Observer{

@Override
public void update(Observable observable, Object data) {

while (!observable.queue.isEmpty()){

     //NETWORK OPERATION!!  
     processRequest(queue.remove());
}

}

}

This is the main class:

public static main(){

HttpRequestQueue qu = new HttpRequestQueue();
Webclient wClient = new WebClient();

qu.addObserver(wClient);

//Now start other application operations
qu.add(new HttpRequest(...)); //Observer's update will be called 1st time
qu.add(new HttpRequest(...)); //Observer's update will be called 2nd time
qu.add(new HttpRequest(...)); //Observer's update will be called 3rd time
}

Now what will be the behavior of the Observer Webclient's update() as when it will be called for the second time, the execution of the first wouldn't have ended.

Sorry if I sound like a dumb.


Solution

  • Long-running operations should be executed in separate threads. If I understood you correctly, the processRequest() is a long-running operation and it will block the application until the processing is finished.

    Well, it should be implemented in similar manner to this one:

    public void processRequest(final HttpRequest req) {
        new Thread() {
            @Override
            public void run() {
                //processing logic
            }
        }.start();
    }
    

    Hence there will be nothing that blocks your application.

    I wanted to know what happens when an Observer is notified multiple times while it's still executing overridden method update(Observable observable, Object obj).

    Well, the Observer will not be notified until processRequest finishes. If everything is executed from a single thread, this operation processRequest will finish and only then the next q.add(new HttpRequest(...)); will execute.