Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: observer-pattern notify in new thread

I have the following problem. Given a Interface EventNotifier for the Observer Pattern:

public interface EventNotifier {
    void newEvent(final String value);
}

A class, which implements this Interface, can register at another class, which calls very often the method newEvent. The Interface is given by a external library, so I cannot change it. Up to now I implemented it with an anonymous class:

Thread t = new Thread(new Runnable() {

    @Override    
    public void run() {

      watcher = new Watcher(new EventNotifier() {

          @Override
          public void newEvent(String value) {
              //do some stuff
              //will be called more than 20 times per second
          }
       });
 });
 t.start();

For better code readability I would like to expose this anonymous class into a new class, which extends Thread (because the handling should be parallel to other things).

How can I write a Thread, which does nothing (no endless-loop etc.), but wait for calling the newEvent method? The problem is, that newEvent will be called more than 20 times a second, so I cannot start a new thread for each call but the whole thing should be in a thread.

I hope you get the problem and somebody can help me.

like image 959
Michael Avatar asked Jan 18 '23 01:01

Michael


1 Answers

What makes your post confusing is that the EventNotifier is in fact an observer/listener (it receives the event, it doesn't fire them), and the Watcher is in fact the notifier (it's the watcher that creates an event and calls the newEvent method).

I'll use the terms observable and observer from now on. The observable fires events, and thus calls the observer's newEvent method.

If you want the event handling to be done in a separate thread, use a BlockingQueue. Start a thread that loops endlessly, and tries to take() from the queue at each iteration. Register an observer to the observable, which simply takes the received event and put() it in the blocking queue.

like image 113
JB Nizet Avatar answered Jan 22 '23 05:01

JB Nizet