[Java] What is Heap Space & Dynamic Memory Allocation?

Different types of memory 

To run Java applications optimally, the JVM divides memory into 
  1. Stack Memory 
  2. Heap Memory.
Things that go into these memories

Whenever new variables and objects are declared, new methods are called or other similar operations are performed, the JVM designates memory to these operations from either the Stack Memory or Heap Space.

    - Heap Memory: 
        It is used for the dynamic memory allocation of Java objects and classes at runtime.
        New objects are always created in the heap space.

    - Stack Memory:
         - References to these objects are stored in the stack memory.

When does the Java heap space gets created?

The heap space is created by the JVM when it starts. The heap is used as long as the application is running.

How does the java heap space gets broken?

Heap space can be broken down into smaller parts called generations, which are:

    - Young Generation: 
        - All new objects are allocated and aged here. A minor garbage collection occurs when this fills up.

    Old or Tenured Generation: 
        - Long surviving objects are stored here.
        - When objects are stored in the Young Generation, a threshold for the object's age is set. When this threshold is reached, the object is moved to the Old Generation.
        - Garbage collection is usually performed in the Old Generation when it's full.

    - Permanent Generation (replaced by Metaspace since Java 8) : 
        - Consists of JVM metadata for runtime classes and application methods.

Java Heap Space Features

    - It is accessed via complex management techniques that include the Young, Old and Permanent Generations.
    - Access to the heap is slower than to the stack memory.
    - The heap is not automatically deallocated. It needs the Garbage Collector to free up unused objects to keep memory usage efficient.
    - The heap is not threadsafe and needs to be guarded by keeping the code properly synchronized.

Java Heap Size

The Java heap size is determined by two JVM attributes, which can be set when launching the application:

    - -Xms to set the initial heap size
    - -Xmx to set the maximum heap size




No comments

Powered by Blogger.