Skip to content

Java infinite loop performance

I have a Thread that only has to work when a certain circumstance comes in. Otherwise it just iterates over an empty infinite loop:

public void run() {
    while(true) {
        if(ball != null) {
             // do some Calculations
        }
    }
}

Does it affect the performance when the loop actually does nothing but it has to check if it has to do the calculation every iteration? Only creating a this Thread when needed is not an option for me, because my class which implements Runnable is a visual object which has be shown all the time.

edit: so is the following a good solution? Or is it better to use a different method (concerning performance)?

private final Object standBy = new Object();

public void run() {
    while(true) {
        synchronized (standBy) {
            while(ball != null)  // should I use while or if here?
                try{ standBy.wait() }
                catch (InterruptedException ie) {}
        }
        if(ball != null) {
             // do some Calculations
        }
}

public void handleCollision(Ball b) {
    // some more code..
    ball = b;
    synchronized (standBy) {
        standBy.notify();
    }
}

Answer

You might want to consider putting the thread to sleep and only waking it up only when your ‘ball’ variable becomes true. There are multiple ways of doing this, from using the very low level, wait and notify statements to using the java.util.concurrent classes which provide a less error prone way of doing this. Have a look at the documentation for the condition interface. A data structure like a BlockingQueue would also be a solution.