1

I am debugging code that has in it expr1 & expr2 where expr1 has a side effect that affects expr2 evaluation result. I suspect that expr2 gets evaluated before expr1, since JLS guarantees left-to-right evaluation for &&, but not necessarily for &. I also suspect that change of evaluation order may be a result of optimization performed by HotSpot (we're running Java 6u20). Do you know if HotSpot can make such an optimization? Better yet, provide any pointers to documentation that either support or eliminate the suspicion. Thanks in advance.

EDIT: Thanks for those suggesting to rewrite the code so it's both correct and readable - you're right, but I already did, so it's not what I am looking for. Unfortunately it is hard to test the change, which is why I'm asking the question here.

4

2 回答 2

6

评估顺序在规范中明确定义:

Java 编程语言保证运算符的操作数看起来是以特定的评估顺序进行评估的,即从左到右。

如果这改变了结果,HotSpot 优化器不应进行导致 expr2 在 expr1 之前被评估的优化。如果这样做,那就是一个错误。

还要注意它说:

建议代码不要严重依赖本规范。

您的代码可以更清楚地重写如下:

int a = expr1;
int b = expr2;
int result = a & b;
于 2010-07-27T18:42:11.390 回答
1

JLS 第 3 版第 15.7 节从左到右讨论评估顺序,但要求不要关键依赖它(短路的除外)

于 2010-07-27T18:47:23.220 回答