1. Overview
A company interview, director of the uncle came over, asked the graph theory and the maximum depth of the stack, and then ^_^
Keep it in mind, today.
2. Code
Packagecom.goodfan.test; Public classJavastacktest {Private intCount = 0; Public voidTeststack () {count++; Teststack (); }; Public voidTest () {Try{teststack (); } Catch(Throwable e) {System.out.println (e); System.out.println ("Stack Height:" +count); } } Public Static voidMain (string[] args) {Newjavastacktest (). Test (); }}
Console output
Java.lang.StackOverflowError
Stack height:11421
3. Summary
The 3.1 Java stack is an important part of the Java Virtual Machine, threading operations in the stack, storing method parameters, and so on.
The stack has a certain size after initialization.
The height of the stack is called the depth of the stack, and the stack depth is affected by the stack frame size.
We know that storing local variables, parameters, running intermediate results, etc. in the stack.
3.2 Add parameters (because the method parameters need to occupy memory, so the stack can be used for the method itself is reduced)
Public void teststack (intint b) { count+ +; Teststack (A, b); }
Console output
Java.lang.StackOverflowError
Stack height:9654
3.3 Further,
3.3.1 increase the number of local variables
Public void teststack (intint b) { int c =5; long d=4l; Count+ +; Teststack (A, b); }
Console output
Java.lang.StackOverflowError
Stack height:7854
3.3.2 increasing the value of a variable
Public void teststack (intint b) { int c =5; long d=47777777777777777l; Count+ +; Teststack (A, b); }
Console output
Java.lang.StackOverflowError
Stack height:7846
It can be seen that the more local variable table content, the larger the stack frame, the lower the stack depth.
Know the depth of the stack, how to use it? What is the use of tuning the JVM?
When we define too many method parameters and local variables, and the bytes are too large, it may cause errors in the program, considering how small the stack depth might be.
This time you need to manually increase the depth of the stack, to avoid errors.
3.4 Adjusting the JVM stack size
C:\Users\rocky fang\documents\mycode>java-xss2m-cp "C:\Users\rocky fang\documents\mycode" javastacktest
Java.lang.StackOverflowError
Stack height:23345
C:\Users\rocky fang\documents\mycode>java-xss5m-cp "C:\Users\rocky fang\documents\mycode" javastacktest
Java.lang.StackOverflowError
Stack height:93213
C:\Users\rocky fang\documents\mycode>java-xss10m-cp "C:\Users\rocky fang\documents\mycode" javastacktest
Java.lang.StackOverflowError
Stack height:423618
Maximum Java Stack depth