Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method invocation order with chained methods

Tags:

java

Given is the following Java code example:

builder.something()
       .somethingElse()
       .somethingMore(builder.getSomething());

Is it guaranteed by the Java Language Specification that getSomething() is invoked after the somethingElse() method or is a Java implementation allowed to reorder the execution?

like image 349
Benedikt Waldvogel Avatar asked Oct 29 '15 23:10

Benedikt Waldvogel


1 Answers

The JLS, Section 15.12.4, guarantees that the target reference is computed before arguments are evaluated.

At run time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. ...

The somethingElse method must be evaluated first, to compute the target reference for the somethingMore method. Then builder.getSomething() is evaluated to supply a value for the parameter to somethingMore. Then somethingMore can be executed.

Because of this rule, JVMs are not allowed to reorder the execution.

like image 180
rgettman Avatar answered Sep 29 '22 02:09

rgettman