简体   繁体   中英

Size taken by stack frame

Java stack create new frame for every method call, But does this frame takes memory on the stack?

To clarify on my question :

public void oneWay()
{
  System.out.println("start");
  get1();
}

private void get1()
{
  System.out.println("get1");
  get2();
}

private void get2()
{
  System.out.println("get2");
}

Output of this is same as :

public void anotherWay()
{
  System.out.println("start");
  System.out.println("get1");
  System.out.println("get2");
}

But does second snippet takes more memory on stack or equal? In short, does stack frame take memory?

EDIT : How much memory does a stack frame take? Is there any specification by Sun, now Oracle?

Yes, naturally. That's why you get a stack overflow if you nest too deep. You can use the -Xss command line switch to modify the stack size, if you find that you need to have a bigger (or smaller) stack for your threads.

The specification seems to allow a lot of freedom for the implementation, so all in all, you can't really rely on stack frame size.

You can count the number of stack frames on the current thread's stack as:

Thread.currentThread().getStackTrace().length

In your case, getting this value in get2 would give you a larger value than getting it directly in oneWay (larger by 2). The exact values depend on where in your code you call oneWay . Although some other programming languages don't necessarily create a stack frame for every function call, this is always the case for Java. The JVM spec states explicitly in §2.6 that "A new frame is created each time a method is invoked." and later "Frames are allocated from the Java Virtual Machine stack". So in Java every method call sets up a stack frame, and every stack frame takes memory on the stack. Even when invoking a function that does nothing, a certain amount of memory is required by the virtual machine to keep track of the stack frame itself.

As stated in Inside the Java Virtual Machine ,

The stack frame has three parts: local variables, operand stack, and frame data. The sizes of the local variables and operand stack, which are measured in words, depend upon the needs of each individual method. These sizes are determined at compile time and included in the class file data for each method. The size of the frame data is implementation dependent.

When the Java virtual machine invokes a Java method, it checks the class data to determine the number of words required by the method in the local variables and operand stack. It creates a stack frame of the proper size for the method and pushes it onto the Java stack.

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