Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 879
SimonH Avatar asked Jun 13 '15 21:06

SimonH


1 Answers

I found the following interesting thing. In task manager, running that infinite loop like that, would consume 17% of my CPU. Now, if I added a simple

Thread.sleep(1)

inside the loop, which is only one milisecond, the CPU use dropped to almost zero as if I was not using the program, and the response time of the program was still pretty good on average (in my case it needed to reply things fast)

like image 163
Samuel Avatar answered Oct 28 '22 21:10

Samuel