Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 793749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T22:12:11+00:00 2026-05-14T22:12:11+00:00

I’m using a framework called Processing which is basically a Java applet. It has

  • 0

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));
  }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T22:12:11+00:00Added an answer on May 14, 2026 at 10:12 pm

    Yes, event handling is the key to your problem. The C# snippet you show also uses event handling to tell listeners that a property is changed. Java also has these PropertyChangeEvent’s, which is used for most Beans. (For example: Swing components use them).

    You can, however, do this manually: (though this isn’t as POJO anymore, but more a Java Bean)

    EventBean.java:

    import java.util.LinkedList;
    import java.util.List;
    
    public class EventBean {
    
        private final List<Listener> listeners = new LinkedList<Listener>();
    
        protected final <T> void firePropertyChanged(final String property,
                final T oldValue, final T newValue) {
            assert(property != null);
            if((oldValue != null && oldValue.equals(newValue))
                    || (oldValue == null && newValue == null))
                return;
            for(final Listener listener : this.listeners) {
                try {
                    if(listener.getProperties().contains(property))
                        listener.propertyChanged(property, oldValue, newValue);
                } catch(Exception ex) {
                    // log these, to help debugging
                    ex.printStackTrace();
                }
            }
        }
    
        public final boolean addListener(final Listener x) {
            if(x == null) return false;
            return this.listeners.add(x);
        }
        public final boolean removeListener(final Listener x) {
            return this.listeners.remove(x);
        }
    
    }
    

    Listener.java:

    import java.util.Collections;
    import java.util.Set;
    import java.util.TreeSet;
    
    // Must be in same package as EventBean!
    public abstract class Listener {
    
        private final Set<String> properties;
    
        public Listener(String... properties) {
            Collections.addAll(this.properties = new TreeSet<String>(), properties);
        }
    
        protected final Set<String> getProperties() {
            return this.properties;
        }
    
        public abstract <T> void propertyChanged(final String property,
                final T oldValue, final T newValue);
    }
    

    And implement your class like this:

    public class MyBean extends EventBean {
    
        private boolean typedA;
    
        public void setTypedA(final boolean newValue) {
            // you can do validation on the newValue here
            final boolean oldValue = typedA;
            super.firePropertyChanged("typedA", oldValue, newValue);
            this.typedA = newValue;
        }
        public boolean getTypedA() { return this.typedA; }
    
    }
    

    Which you can use as:

    MyBean x = new MyBean();
    x.addListener(new Listener("typedA") {
        public <T> void propertyChanged(final String p,
                     final T oldValue, final T newValue) {
            System.out.println(p + " changed: " + oldValue + " to " + newValue);
            // TODO
        }
    });
    
    x.setTypedA(true);
    x.setTypedA(false);
    x.setTypedA(true);
    x.setTypedA(true);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 494k
  • Answers 494k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Your pattern doesn't match your example URL. Assuming your example… May 16, 2026 at 10:59 am
  • Editorial Team
    Editorial Team added an answer There are quite some impressive substring algorithms. Often the Boyer-Moore… May 16, 2026 at 10:59 am
  • Editorial Team
    Editorial Team added an answer COM+ was Microsoft's offering in the battle for the middle… May 16, 2026 at 10:59 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
Does anyone know how can I replace this 2 symbol below from the string
In order to apply a triggered animation to all ToolTip s in my app,
I want use html5's new tag to play a wav file (currently only supported
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
Seemingly simple, but I cannot find anything relevant on the web. What is the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.