Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the execution flow of a method wait when you call another method within it?

Say you have the following method in MyClass

public class MyClas{
  public void startWork(){
    YourClass.doSomeWork();
    //more things to do in this method
  }
}

and YourClass looks like this:

public class YourClass{
  public static void doSomeWork(){
    // a lot of work to do here
    // maybe even invoke other methods in some other classes
  }
}

now what I am wondering is when the code YourClass.doSomeWork(); is executed in startWork() method, will the script continue to the next line in the same method or wait until doSomeWork() in YourClass finishes its execution?

Note that doSomeWork() doesn't return anything.

like image 939
sticky_elbows Avatar asked Dec 11 '22 05:12

sticky_elbows


2 Answers

The default semantics in most languages, and especially in Java is of course that code gets executed sequentially.

Meaning: unless you do additional things, such as submitting a task into an ExecutorService (or creating a Thread object and calling its start() method), then of course an outer method will execute all calls in sequence, and each inner call needs to finish before the next one is executed.

In other words: unless you use specific constructs in your source code, things get executed by a single thread, in the exact order that you put in your code. And yes, things can get more complicated, as instructions can be re-ordered at various levels, but these aspects of the Java memory model aren't relevant for the basic question asked here).

like image 124
GhostCat Avatar answered Jan 16 '23 15:01

GhostCat


It will wait until doSomeWork finished.

If you want to call doSomeWork asynchronouly and the next procedure of startWork does not rely on the result of doSomeWork, you can take use of some concurrent framework, for example, Executor.

like image 44
xingbin Avatar answered Jan 16 '23 15:01

xingbin