Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my JVM doing some runtime loop optimization and making my code buggy?

Consider the following java code:

public int main() {
    int i = 1111;

    for (; rules(i) != true && i < Integer.MAX_VALUE; i++) {
        //LOG.debug("Testing i: " + i);
    }

    System.out.println("The mystery number is: " + i);

    return i;
}

protected boolean rules(int nb) {
    //...
}

I've found out that even when the for loop continuation evaluation is true, the loop will stop being executed when its body is empty.

The final result of main is wrong (i is 16698 about 98% of the time and sometimes a little higher/lower).

If I uncomment the LOG statement from the loop body, the loop will keep on running until the loop continuation evaluation is false.

The JVM I'm using is MacOS X VM 1.6.0.

  • Is it doing some sort of runtime optimization?
  • Can this runtime optimization be considered a bug?
  • Or is it said somewhere in Java specs that for continuation evalution should not run functional operations?

ps: the full code source + its unit test are available here: https://gist.github.com/dirtyhenry/5804130

UPDATE:

  • I've run the code via junit only. Could junit be responsible for this behavior?

UPDATE 2:

java -version

returns:

java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-456-11M4508)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-456, mixed mode)
like image 712
Dirty Henry Avatar asked Jun 18 '13 10:06

Dirty Henry


Video Answer


1 Answers

I had a similar issue here: Near empty Java For-Loop acts strange You should try using JVM 1.7 or try using a while loop:

public int main() {
    int i = 1111;

    while(i < Integer.MAX_VALUE){
        if (!rules(i)) {
            break;
        }
        i++
    }

    System.out.println("The mystery number is: " + i);

    return i;
}
like image 177
Zaide Chris Avatar answered Oct 28 '22 23:10

Zaide Chris