Stack vs Heap Memory
Whenever we create objects it occupies space in the heap memory while the reference of that object creates in the stack.
Stack Memory // get diagram for its content’s organisation
java.lang.StackOverFlowError
The stack memory is a physical space (in RAM) allocated to each thread at run time. It is created when a thread creates. Memory management in the stack follows LIFO (Last-In-First-Out) order because it is accessible globally. It stores the variables, references to objects, and partial results. Memory allocated to stack lives until the function returns. If there is no space for creating the new objects, it throws the java.lang.StackOverFlowError. The scope of the elements is limited to their threads. The JVM creates a separate stack for each thread.
- can increase the stack size by using the JVM option -Xss
Heap Memory
java.lang.OutOfMemoryError
does not follow any order like the stack. It dynamically handles the memory blocks using Garbage Collector
- can increase or decrease the heap memory size by using the -Xmx and -Xms JVM options
“Each JVM thread has a private Java virtual machine stack, created at the same time as the thread. A JVM stack stores frames, also called “stack frames”. A JVM stack is analogous to the stack of a conventional language such as C — it holds local variables and partial results, and plays a part in method invocation and return.”
A stack frame is created every time a new method is called.
Therefore, you can visualize that a single stack has a pile of stack frames that look like this:
As that quote mentions, each thread has its own stack, so in a multi-threaded application there are multiple stacks, and each stack has its own stack of frames.
“When a thread invokes a Java method, the JVM creates and pushes a new frame onto the thread’s stack. This new frame then becomes the current frame. As the method executes, it uses the frame to store parameters, local variables, intermediate computations, and other data.”
As the method is executed, the code can only access the values in the current stack frame, which you can visualize as being the top-most stack frame.
References
Java Stack Frames
stack regards to recursion
javatpoint source