JVM.MemoryManagement.What is the heap memory in JVM, and how is it used?

The Heap memory in JVM is the runtime memory where all Java objects and instance variables are stored. It is the largest part of the JVM memory and is shared among all threads.

How Heap Memory is Used in JVM

  1. Object Allocation:
    • Whenever new is used to create an object, memory is allocated in the Heap.
    • Example
class Car {
    String model;
}
Car myCar = new Car(); // Allocated in Heap

Garbage Collection (GC):

  • JVM automatically reclaims memory of unused objects through Garbage Collection (GC).
  • Objects without references become eligible for GC.

Divided into Different Generations (Memory Segments):

  • The Heap is divided into:
    • Young Generation (Short-lived objects)
    • Old Generation (Tenured Space) (Long-lived objects)
    • Metaspace (Class metadata storage)

Heap Memory Structure

1️⃣ Young Generation (New Objects)

  • Stores newly created objects.
  • It has three parts:
    • Eden Space – New objects are first allocated here.
    • Survivor Space S0 & S1 – Objects that survive minor GC move between these two spaces.
  • Garbage Collection: Minor GC runs frequently here.

2️⃣ Old Generation (Long-Lived Objects)

  • Objects that survive multiple GC cycles move here.
  • GC here is less frequent but more expensive (Major GC or Full GC).

3️⃣ Metaspace (Class Metadata)

  • Stores class-related information (replacing PermGen in Java 8+).
  • Dynamically grows as needed.

How JVM Manages Heap Memory Efficiently

  • JVM tunes heap memory dynamically.
  • Uses GC algorithms (like G1GC, Parallel GC, ZGC) to manage memory efficiently.
  • Developers can configure Heap Size:
    • -XmsInitial Heap Size
    • -XmxMaximum Heap Size

Example:

java -Xms512m -Xmx2g MyApp

Heap Memory vs Stack Memory

FeatureHeap MemoryStack Memory
StoresObjects, instance variablesLocal variables, method calls
ScopeShared among threadsEach thread has its own stack
LifetimeUntil Garbage CollectionUntil method execution ends
PerformanceSlower due to GCFaster (direct access)

Would you like to explore Garbage Collection tuning or Heap memory optimization strategies? 🚀

This entry was posted in Без рубрики. Bookmark the permalink.