I read JLS 15.7.4 and 15.12.4.2 , but it doesn’t guarantee that there will be no compiler / runtime optimization that will change the order in which the method arguments are evaluated.
Assume the following code:
public static void main (String[] args) { MyObject obj = new MyObject(); methodRelyingOnEvalOrder(obj, obj.myMethod()); } public static Object methodRelyingOnEvalOrder(MyObject obj, Object input) { if (obj.myBoolean()) return null; else return input; }
Is it guaranteed that the compiler or runtime will not perform false optimizations such as the following? This optimization may seem right, but it’s wrong when the order of evaluation makes sense.
In the event that calling obj.myMethod changes the value that obj.myBoolean will return, it is imperative that obj.myMethod be called first, since methodRelyingOnEvalOrder requires that this change occur first.
//******************************* //Unwanted optimization possible: //******************************* public static void main (String[] args) { MyObject obj = new MyObject(); methodRelyingOnEvalOrder(obj); } public static Object methodRelyingOnEvalOrder(MyObject obj) { if (obj.myBoolean()) return null; else return obj.myMethod(); } //*******************************
If possible, please show some sources or Java documentation that support your answer.
Note: Please do not ask to rewrite the code. This is a specific case when I ask a question about guaranteeing the evaluation order and guaranteeing compiler / runtime optimization. The execution of obj.myMethod must be executed in the main method.
source share