Java memory management

Heap and Stack Memory Allocation

Generally java memory is divided into two big parts :

  1. Heap
  2. Stack

Heap is huge amount of memory compare to stack. 1024 MB is default value of heap size in java. Java Heap Space is used throughout the application, but Stack is only used for the method — or methods — currently running.

Stack :
Stack memory is responsible for holding references to heap objects and for storing the value types (also known as java primitive types) which holds the value itself rather than reference to an object from the heap.

Heap :
This is a part of memory stores the actual object in the memory, those are referenced by variables from the stack.

StringBuilder builder = new StringBuilder();

The new keyword is responsible for ensuring that there is enough free space on heap.

System.gc() method : Calling the gc method suggests that JVM expend the effort towards recycling unused objects in order to make the memory they currently occupy available for reuse.

Runtime.getRuntime().gc() method : Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.

Ramesh Kumar S avatar

Posted by

Leave a comment