Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it that the code below behaves differently in Java 1.6 and 1.7

Tags:

java

The code below

public class Test16Jit {
  public static void main(String[] s) {
      int max = Integer.MAX_VALUE;
      int i = 0;
      long li = 0;
      while (i >= 0) {
          i++;
          li++;
          if (i > max) {
              System.out.println("i is : " + i);
              System.out.println("max is : " + max);
              System.out.println("Woo!! something really went wrong");
          }
      }
      System.out.println("Value of i: " + i);
      System.out.println("Total # of iterations: " + li);      
  }
}

Outputs below in java 1.7x

Value of i: -2147483648
Total # of iterations: 2147483648

Outputs below in Java 1.6x

i is : 2147483636
max is : 2147483647
Woo!! something really went wrong
Value of i: -2147483648
Total # of iterations: 2147483648

Is there a reason for this behavior?

Also if I change

int max = Integer.MAX_VALUE; -> final int max = Integer.MAX_VALUE;

It behaves exactly same in 1.6x and 1.7x

like image 924
Puru-- Avatar asked Jul 25 '16 23:07

Puru--


1 Answers

It seems like one of many examples of a family of errors related to this one caused by the JIT compilation (I picked this one due to similarity of code, feel free to explore others - they are quite interesting!):

http://bugs.java.com/view_bug.do?bug_id=6196102

EVALUATION

Problem is with canonicalization of loop exit test in preparation for loop transformation.

do while (++i <= limit)

becomes

do while (++i < limit+1)

This isn't correct when limit is maxInt.

Some issues were fixed in 1.7, which could explain your results.

like image 54
mszymborski Avatar answered Nov 15 '22 15:11

mszymborski