为什么我的JVM为什么要进行一些运行时循环优化并使代码出错? [英] Why is my JVM doing some runtime loop optimization and making my code buggy?

查看:104
本文介绍了为什么我的JVM为什么要进行一些运行时循环优化并使代码出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Java代码:

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) {
    //...
}

我发现,即使for循环连续性评估为true,当循环的主体为空时,该循环也将停止执行.

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.

main的最终结果是错误的(i大约是98%的时间是16698,有时高一点/低一点).

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

如果我从循环主体中取消注释LOG语句,则循环将继续运行,直到循环继续评估为false为止.

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

我正在使用的JVM是MacOS X VM 1.6.0.

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

  • 它是否正在进行某种运行时优化?
  • 可以将这种运行时优化视为错误吗?
  • 还是在Java规范的某个地方说过,为了继续评估,不应该运行功能性操作?
  • 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:此处提供完整的代码源及其单元测试: https://gist.github. com/dirtyhenry/5804130

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

更新:

  • 我仅通过junit运行代码. junit可能对此行为负责吗?

更新2:

java -version

返回:

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)

推荐答案

我已经看到一些关于SO的参考,这些参考仅在经过10000次以上的迭代后才出现循环优化.也许这就是为什么魔术数"通常在16000左右的原因?

I have seen a few references on SO to loop optimisation only occurring after more than 10000 iterations. Perhaps that is why the "magic number" is often around 16000?

这里有一个很好的讨论

用于优化循环语句的JVM选项

这篇关于为什么我的JVM为什么要进行一些运行时循环优化并使代码出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆