Search code examples
javaoopexecution

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.


Solution

  • 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).