Watching a variable for changes without polling.

Posted by milkfilk on Stack Overflow See other posts from Stack Overflow or by milkfilk
Published on 2010-05-12T21:32:59Z Indexed on 2010/05/12 22:24 UTC
Read the original article Hit count: 335

Filed under:
|
|
|

I'm using a framework called Processing which is basically a Java applet. It has the ability to do key events because Applet can. You can also roll your own callbacks of sorts into the parent. I'm not doing that right now and maybe that's the solution. For now, I'm looking for a more POJO solution. So I wrote some examples to illustrate my question.

Please ignore using key events on the command line (console). Certainly this would be a very clean solution but it's not possible on the command line and my actual app isn't a command line app. In fact, a key event would be a good solution for me but I'm trying to understand events and polling beyond just keyboard specific problems.

Both these examples flip a boolean. When the boolean flips, I want to fire something once. I could wrap the boolean in an Object so if the Object changes, I could fire an event too. I just don't want to poll with an if() statement unnecessarily.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
 * Example of checking a variable for changes.
 * Uses dumb if() and polls continuously.
 */
public class NotAvoidingPolling {

    public static void main(String[] args) {

        boolean typedA = false;
        String input = "";

        System.out.println("Type 'a' please.");

        while (true) {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);

            try {
                input = br.readLine();
            } catch (IOException ioException) {
                System.out.println("IO Error.");
                System.exit(1);
            }

            // contrived state change logic
            if (input.equals("a")) {
                typedA = true;
            } else {
                typedA = false;
            }

            // problem: this is polling.
            if (typedA) System.out.println("Typed 'a'.");
        }
    }
}

Running this outputs:

Type 'a' please. 
a
Typed 'a'.

On some forums people suggested using an Observer. And although this decouples the event handler from class being observed, I still have an if() on a forever loop.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
import java.util.Observer;

/* 
 * Example of checking a variable for changes.
 * This uses an observer to decouple the handler feedback 
 * out of the main() but still is polling.
 */
public class ObserverStillPolling {

    boolean typedA = false;

    public static void main(String[] args) {

        // this
        ObserverStillPolling o = new ObserverStillPolling();

        final MyEvent myEvent = new MyEvent(o);
        final MyHandler myHandler = new MyHandler();
        myEvent.addObserver(myHandler); // subscribe

        // watch for event forever
        Thread thread = new Thread(myEvent);
        thread.start();

        System.out.println("Type 'a' please.");

        String input = "";

        while (true) {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);

            try {
                input = br.readLine();
            } catch (IOException ioException) {
                System.out.println("IO Error.");
                System.exit(1);
            }

            // contrived state change logic
            // but it's decoupled now because there's no handler here.
            if (input.equals("a")) {
                o.typedA = true;
            }
        }
    }
}

class MyEvent extends Observable implements Runnable {
    // boolean typedA;
    ObserverStillPolling o;

    public MyEvent(ObserverStillPolling o) {
        this.o = o;
    }

    public void run() {

        // watch the main forever
        while (true) {

            // event fire
            if (this.o.typedA) {
                setChanged();

                // in reality, you'd pass something more useful
                notifyObservers("You just typed 'a'.");

                // reset
                this.o.typedA = false;
            }

        }
    }
}

class MyHandler implements Observer {
    public void update(Observable obj, Object arg) {

        // handle event
        if (arg instanceof String) {
            System.out.println("We received:" + (String) arg);
        }
    }
}

Running this outputs:

Type 'a' please.
a
We received:You just typed 'a'.

I'd be ok if the if() was a NOOP on the CPU. But it's really comparing every pass. I see real CPU load. This is as bad as polling. I can maybe throttle it back with a sleep or compare the elapsed time since last update but this is not event driven. It's just less polling. So how can I do this smarter? How can I watch a POJO for changes without polling?

In C# there seems to be something interesting called properties. I'm not a C# guy so maybe this isn't as magical as I think.

private void SendPropertyChanging(string property)
{
  if (this.PropertyChanging != null) {
    this.PropertyChanging(this, new PropertyChangingEventArgs(property));
  }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about events