Memory Management in Java - Stack and Heap

Memory Management in Java - Stack and Heap 

Memory management is a mechanism to allocate memory when new objects are created and free it when no longer needed.

In Java, the memory is divided into 2 segments:
  1. STACK
  2. HEAP

STACK

The stack is the place where any local variables and methods are stored.

The lifetime of variables on the stack is governed by the scope of the code. The scope is usually defined by an area of code in curly brackets, such as a method call, or for or while loop. Once the execution has left that scope, those variables declared in the scope are removed from the stack.

When the stack memory fills up, and eventually any more method calls will not be able to allocate their necessary variables. This results in a StackOverflowError.

HEAP

The heap is the place where objects, instance variables and static variables are stored.



The new keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError is thrown, and the JVM exits


The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.

Class definitions, String Constant Pool and static variables will be placed in PermGen space in Heap.



For Example:

class A {}


public class B {

    A instanceVariable1; //Instance Variable: instanceVariable1
    String instanceVariable2; //Instance Variable: instanceVariable2
   
    public static void main(String[] args) {
        B localVariable; //Local Variable: localVariable
        localVariable = new B();
        localVariable.method1(localVariable);
    }
   
    public void method1 (B b) { //Local Variable: b
        b.method2("Test");
    }
   
    public void method2 (String s) { //Local Variable: s
        instanceVariable2 = s;   
    }
}


Instance           Variables
Local Variables     
Methods 
Objects 
instanceVariable1
localVariable
main
new B()
instanceVariable2
b
method1
new A()

s
method2
String

Pictorial representation of objects, methods and variables



















Comments

Popular posts from this blog

Implementation of Documentum Business Object Framework (BOF)

Create a web application in 5 minutes using Spring Boot and Maven

Creating Session in Documentum