According to my understanding, a Java compiler, Java VM, and even the underlying hardware is free to reorder a Java program's statements for the sake of performance as long as the program's observable behavior is preserved. So far, so good. But it seems to me that due to Java's exception mechanism, (almost) no reordering satisfies this condition. Let me illustrate my point with a simple program (note that I'm only considering single-threaded programs):
public class Reordering {
public static void main(String[] args) {
int x, y;
x = 1;
try {
x = 2;
y = 0 / 0;
} catch (Exception e) {
} finally {
System.out.println("x = " + x);
}
}
}
First x is assigned 1. Within the try block, x is assigned 2. The next statement attempts to perform a division by zero, which triggers an ArithmeticException. After executing the (empty) catch block, control is transferred to the finally block, where the value of x (2) is printed to the console. (I'm not exactly sure how "observable behavior" is defined for Java programs. Anyway, printing to the console should certainly count as such.)
At first sight, the two statements in the try block seem like perfectly safe candidates for reordering, because they do not have any apparent dependency. However, if they are exchanged, the resulting program no longer prints "2" but "1", because the ArithmeticException now occurs before x is assigned 2!
Adding the fact that virtually any Java statement may trigger an exception (possibly thrown by the VM itself) and virtually any code may be executing within a try block (depending on the actual call chain), we seem to arrive at the conclusion that virtually any reordering in any program is "observable" and therefore disallowed. Wait, have I just stumbled across the definitive answer to "Why is Java so slow"? Oops, just joking! Anyway, I'm curious to learn where my train of thought goes wrong.
Thanks for your input, and Greetings from Austria!
fzitters
P.S. Can you think of a forum better suited for this kind of topic?