Is this a JVM bug or “expected behavior”?

ぐ巨炮叔叔 提交于 2019-11-29 20:14:30
Kevin Bourrillion

Known bug. Related to

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

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6357214

and others.

I think they're considered low-priority to fix because they don't come up in the real world.

This is bizarre. It certainly looks like a bug somewhere. I get the same results every time with the same code, but trivial changes to the code change the result. For example:

public class Test {
  public static void main(String[] args) {
    int i;
    int count = 0;
    for (i = 0; i < Integer.MAX_VALUE; i+=2) {
      count++;
    }
    System.out.println(i);
    System.out.println(i < Integer.MAX_VALUE);
  }
}

... always prints 2147483640 and true

whereas this:

public class Test {
  public static void main(String[] args) {
    int i;
    for (i = 0; i < Integer.MAX_VALUE; i+=2) {
    }
    System.out.println(i);
    System.out.println(i < Integer.MAX_VALUE);
  }
}

always prints -2147483648 and true.

Very, very weird.

(That's running an OpenJDK 1.6 VM on Linux.)

EDIT: Running OpenJDK 1.7 on Windows 7, I don't see the problem:

java version "1.7.0-ea"
Java(TM) SE Runtime Environment (build 1.7.0-ea-b78)
Java HotSpot(TM) Client VM (build 17.0-b05, mixed mode, sharing)

Try adding System.out.println(count);

I wonder if there is optimization occurring because count is never read from.

Edit - another answer gave the link to bugs in Oracle's bug tracker. Drawing from that:

  • 6196102 in particular mentions that there is a canonicalization bug where Integer.MAX_VALUE is concerned.
  • Java must be trying to optimize the loop because count is never read from.

However, this is unlikely to occur in practice, because:

  • Integer.MAX_VALUE is an unlikely loop guard
  • Usually loops do work that wouldn't allow this optimization in the first place

This seems to be a loop optimizations as I observe the same result but IF I also print out count then the result changes.

I.e.

    int i;
    int count = 0;
    for(i=0; i < Integer.MAX_VALUE; i+=2){
      count++;
    }
    System.out.println(count);
    System.out.println(i++);

Produces 2147483638 while the original code produces 457158 (or similar)

java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)

working as expected. infinite loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!