Why does the code below behave differently in Java 1.6 and 1.7

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 the same in 1.6x and 1.7x

+8
java
source share
1 answer

This seems to be one of many examples of a family of errors related to this caused by JIT compilation (I chose this because of the similarity of the code, feel free to investigate others - they are quite interesting!):

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

EVALUATION

The problem is the canonization of the loop exit test in preparation for the loop conversion.

do while (++i <= limit)

becomes

do while (++i < limit+1)

This is not true when limit maxInt.

Some issues have been fixed in 1.7, which may explain your results.

+7
source share

All Articles