It is an implementation detail as to whether the primitive type or a reference type will really go into stack or heap
The reference type just stores the address, but the actual object is always stored in heap (for example by using new keyword)
The following is general implementation but not really necessary
If you have a variable that needs to be accessed across different methods or some data that needs to be accessible after the method has run, that is going to live on the heap (for example static variables)
Class fields (primitive or reference type) go to heap
local variables (primitive or reference type) and method arguments are stored in stack frame unless they are part of closure (anonymous class or lambda)
Heap has items stored in any order
Adding Items to Heap has higher overheads than adding items to stack
class MyClass { private int x = 3; // heap private Point point = new Point(3, 4); // heap public void run() { int y = 7; // stack Point point = new Point(y, y * y); // stack int z = 9; // heap because it is enclosed in closure new Thread(() -> { z++; }).start(); }}
The stack stores stack frames (containing local variables and partial results)
Call stack is also known as execution stack
The stack frame stores information about methods that have not yet terminated. The information includes the address of a method, parameters, local variables, intermediate computations, and some other data
A new stack frame is added when the execution enters a method. And the stack frame is removed from the call stack if the execution of the method is done
When your stack contains too many stack frames, it can be overflowed. It leads to the StackOverflowError that will stop the execution
Stack Trace
Stack trace represents call stack which consist of list of StackTraceElement
Young and Older Generations are served by different Garbage Collectors.
Minor:
aka young generation garbage collection
works on young generation: eden + survivor spaces
collect and reclaim memory that is used by short-lived objects
Major:
aka old-generation garbage collection
collect and reclaim memory that is used by long-lived objects (objects that survive multiple minor garbage collections and are promoted to the old generation)
Full:
memories from all generations are collected and reclaimed
Full GC runs Minor first followed by Major
normally takes longer to complete than a minor or major garbage collection which causes that app to pause temporarily
Garbage collection issues
symptoms:
long garbage collection pauses
frequent collections
excessive CPU consumption
diagnosis:
analyze garbage collection logs
choose appropriate GC
fine tune GC parameters
enable GC logging: -XX:PrintGCDetails or verbose:gc