The Java VM stack is thread-private, and its lifecycle is synchronized with threads
Every time a thread executes into a method, the JVM creates a stack frame (for storing basic data types, object pointers, return values, etc.) and presses the stack frame onto the stack.
Code Example:
public class Example {
public static void main(String[] args) {
Example example = new Example();
example.m1();
}
public void m1() {
int x = 0;
m2();
}
public void m2() {
Apple y = new Apple();
m3();
}
public void m3() {
float z = 1.0f;
}
}
Execute the process:
- First, the program is started and the main() method goes on the stack.
- The m1() method then goes on the stack and declares the int type variable x = 0. Note that either x or 0 is stored in the stack frame.
- Next, the m2() method goes on the stack, creates an Apple object, and is assigned to the variable y. Note that the actual Apple object is created in Java heap memory, not on the thread stack, and only the reference to the Apple object and the variable y are contained in the stack frame.
- Finally, the m3() method goes on the stack and declares the float variable z = 1.0f. Similarly, both z and 1.0f are stored in the stack frame.
When the method execution is complete, all the thread stack frames will be out of the stack one by one in the order of last-in-first-out until the stack is empty
The default size of the Java thread stack is determined by the operating system and is typically 1MB or 2MB. if you need to resize the thread stack, you can use the-Xss
parameter to set. In practice, the default thread stack size is usually sufficient to meet the needs, and you only need to consider adjusting the size if you encounter a thread stack overflow error.
Once the recursion gets too deep and the thread stack grows beyond the allowed stack capacity, a *Error is thrown.
So what are memory leaks and memory overflows?
- Memory overflow (out of memory): when a program requests memory, there is not enough memory space for it to use.
- Memory leak (memory leak): refers to the program after the application of memory, unable to release the memory space that has been applied for, which leads to the memory is gradually occupied.
- memory leak This will eventually lead to out of memory。
Reasons why a memory overflow exception is thrown (including but not limited to):
- If the new thread fails to request the stack, an OutOfMemoryError error is thrown.
- Or an OutOfMemoryError error is also thrown when the JVM cannot allocate space for the creation of an object.
Summary:
- *Error: recursion is too deep, recursion has no exit.
- MemoryLeak: After requesting memory, the requested memory space cannot be freed.
- OutOfMemoryError: JVM space overflow, create objects faster than GC recovery.