Stack vs Heap - Java

STACK

  • Stack is a memory space, reserved by operating system for our process.
  • Size of stack memory is fixed, it is determined in the compiler phase based on variables declaration and other compiler options.
  • When memory is full, then java runtime throws java.lang.StackOverflowError
  • We can use –Xss to define the size of stack memory.

  • Method invocation and local variables lives in stack memory
  • Stack memory used for execution of a thread
  • Remember that Stack memory is always referenced in LIFO (Last-In-First-Out) order, It does means when we call a method, it will be on top of call stack.
  • Method stack exists only till life of method, from the calling until the return.

  • Local variables are also known as slack variables, because they are on the method stack, they exist as long as the method is executed.
  • If the local variable is a reference to an object, only the variable goes on the stack.
  • main method is a special method (the process starts and ends with main) its local variables exist for the entire execution of the process.
  • static variables, are managed in the same way, only difference is that they are stored on the process stack, before using that stack for methods stacks.Remember that, Now Java only stores primitives on the stack.
*Note : it is important to establish that the stack is limited and its size is fixed, once the process has started, it can’t change the stack size

 




HEAP

  • Java Heap space is used by java runtime to allocate memory to Objects and JRE classes
  • Remember whenever we create any object, it’s always created in the Heap space.
  • The JVM allocates Java heap memory from the Operating System and then manages the heap space for the Java application.
  • When an application creates a new object, the JVM sub-allocates a contiguous area of heap memory to store it.
  • When heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error
  • We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory.
  • Remember An object in the heap that is referenced by any other object is "live" and remains in the heap as long as it continues to be referenced
  • Objects that are no longer referenced are garbage.The JVM performs a garbage collection (GC) to remove these objects.
  • Remember, All instance variable lives in the heap.





=============Thank you=============



Comments