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

前端 未结 2 554
傲寒
傲寒 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:31

    In addition to the argument evaluation order, the overview of the steps preformed when invoking a method, and their order, explained in section 15.12.4. Run-Time Evaluation of Method Invocation, makes it clear that all argument evaluations are performed before executing the method's code. Quote:

    At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

    The case you presented where an argument is only evaluated after control has been transferred to the method code is out of the question.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题