Is Java evaluation order guaranteed in this case of method call and arguments passed in

前端 未结 2 567
傲寒
傲寒 2021-01-18 11:11

I did some reading up on JLS 15.7.4 and 15.12.4.2, but it doesn\'t guarantee that there won\'t be any compiler/runtime optimization that would change

2条回答
  •  轮回少年
    2021-01-18 11:40

    The bit of the JLS you referred to (15.7.4) does guarantee that:

    Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

    and also in 15.12.4.2:

    Evaluation then continues, using the argument values, as described below.

    The "appears to" part allows for some optimization, but it must not be visible. The fact that all the arguments are evaluated before "evaluation then continues" shows that the arguments are really fully evaluted before the method executes. (Or at least, that's the visible result.)

    So for example, if you had code of:

    int x = 10;
    foo(x + 5, x + 20);
    

    it would be possible to optimize that to evaluate both x + 5 and x + 20 in parallel: there's no way you could detect this occurring.

    But in the case you've given, you would be able to detect the call to obj.myMethod occurring after the call to obj.myBoolean(), so that wouldn't be a valid optimization at all.

    In short: you're fine to assume that everything will execute in the obvious way here.

提交回复
热议问题