简体   繁体   中英

how does threads and method calls gets allocated on stacks in java?

Each thread in the JVM gets its own stack and they are private. The common resources are accessible from the Heap, which are available to all threads. Let's consider the following code:

public class Test {
   public static int getNum(num) {
      return num;
   }
   public static void main(String[ ] args) {
       int x = getNum(5);
       System.out.println(x);
   }
}

Once the Test class is loaded, there is one thread which is the main that gets executed. The method getNum is stored in the method area of the non-heap memory, according to this article http://javapapers.com/core-java/java-jvm-memory-types/

A stack for the main thread is allocated. Now I have two method calls inside this thread. One is getNum which returns an int , and next is System.out.println (static method of Printstream class).

So do I get to make a new Stack inside the main stack where the first method call gets executed and it returns to main thread to store in variable x and a new stack for println whose return type is void? how does this progressive stack work? or am I getting something wrong here...

I think you are missing the difference between a stack and a stack frame .

There is one stack per thread. Each stack consists of frames. When main performs the first method call, a new stack frame gets allocated, then getNum is called, and then the frame gets deallocated. Now it's turn to call println . Again, a new stack frame is allocated, the call is performed, and the frame gets deallocated. If println makes some method calls of its own, new frames get allocated and deallocated on the same stack to accommodate the call sequence. Stack frames get destroyed in the order opposite to their creation order (that's the reason why this structure is called a "stack" in the first place).

Note that allocating and deallocating stack frames is very efficient, because it's often an operation supported directly by the CPU's hardware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM