My simple library

..of useful code



Chapters

JVM Memory Areas

JVM defines various runtime data areas which are used during execution of a program. Some of the areas are created by the JVM whereas some are created by the threads that are used in a program. However, the memory area created by JVM is destroyed only when the JVM exits. The data areas of thread are created during instantiation and destroyed when the thread exits. These areas include:

  • Heap Area
  • Method Area
  • JVM Stacks
  • Native Method Stacks
  • Program Counter (PC) Registers

1. Heap Area

Heap is a shared runtime data area where objects and arrays are stored. It is created when the JVM starts.

  • The memory in the heap is allocated for all the class instances and arrays.
  • Heap can be of fixed or dynamic size depending upon the system's configuration.
  • JVM allows user to adjust the heap size.
  • When the new keyword is used the object is allocated in the heap and its reference is stored in the stack.
  • There exists one and only one heap for a running JVM process.
Scanner sc = new Scanner(System.in);

Here, the Scanner object is stored in the heap and the reference sc is stored in the stack.

Note: Garbage collection in heap area is mandatory.

Heap Memory Characteristics

  • Heap memory is allocated dynamically during program execution.
  • Unlike stack memory, heap memory is not freed automatically when a function ends.
  • The name heap has no relation to the heap data structure; it simply refers to a large pool of memory available for dynamic allocation.
  • Heap allocation is less safe than stack allocation because heap data is accessible by multiple threads.

Key Features of Heap Allocation

  • If heap memory is full, JVM throws an error: java.lang.OutOfMemoryError.
  • Automatic deallocation does not happen; a garbage collector is needed to free unused memory.
  • Slower than stack memory due to manual allocation and garbage collection.
  • Less thread-safe, as heap memory is shared among all threads.
  • Typically larger in size compared to stack memory.
  • Heap memory persists as long as the entire application is running.

Heap Memory Regions

  • Young Generation: The area within the heap where new objects are generally allocated.
  • Old Generation: The area within the heap where long-lived objects are stored after surviving multiple garbage collection cycles.
  • Permanent Generation: Stores metadata about classes and methods (Note: Removed in Java 8, replaced with Metaspace).

2. Method Area

  • Method area is a logical part of the heap and it is created when the JVM starts.
  • Method area is used to store class-level information such as class structures, Method bytecode, Static variables, Constant pool, Interfaces.
  • Method area can be of fixed or dynamic size depending on the system's configuration.

Note: Though method area is logically a part of heap, it may or may not be garbage collected even if garbage collection is compulsory in heap area.

class Geeks {
    // static variables are stored in the Method Area
    static int v = 100;

    // instance variables are stored in the Heap
    int i = 10;

    public void Display()
    {
        // local variables are stored in the Stack
        int s = 20;

        System.out.println(v);
        System.out.println(s);
    }
}

public class Main {
    public static void main(String[] args) {
        Geeks g = new Geeks();

        // Calling the Display method
        g.Display();
    }
}
  • Static variables are stored in the Method Area.
  • Instance variables are stored in the Heap.
  • Local Variables are stored Stack.

3. JVM Stacks

  • A stack is created when a thread is created, and the JVM stack is used to store method execution data, including local variables, method arguments, and return addresses.
  • Each Thread has its own stack, ensuring thread safety.
  • Stacks size can be either fixed or dynamic, and it can be set when the stack is created.
  • The memory for stack needs not to be contiguous.
  • Once a method completes execution, its associated stack frame is removed automatically.

How Stack Allocation Works

  • Memory is allocated in contiguous blocks within the call stack.
  • The size of memory required is already known before execution.
  • When a function is called, its local variables are allocated on the stack.
  • Once the function finishes execution, the allocated memory is automatically freed.
  • The programmer does not need to handle allocation or deallocation.
  • Since stack memory is freed when a function completes, it is also called temporary memory allocation.

Key Features of Stack Allocation

  • Memory is available only while the function is running.
  • Automatic deallocation occurs when the function ends.
  • If the stack memory is full, an error like java.lang.StackOverflowError occurs in Java.
  • Safer than heap memory, as data can only be accessed by the owner thread.
  • Faster than heap allocation due to automatic memory management.

Note:

  • Stack memory stores references to objects not the object themselves.
  • Each thread in Java application has its own stack.

4. Native Method Stacks

  • Native method stack is also known as C stacks.
  • Native method stacks are not written in Java language.
  • This memory is allocated for each thread when it is created and can have either a fixed or dynamic size.
  • Native method stacks handle the execution of native methods that interact with the Java code.

Garbage Collector

Working of a Garbage Collector

  • The Garbage collector in Java automatically removes the unused objects that are no longer needed. It runs in the background to free up memory.
  • Garbage collector finds objects that are no longer needed by the program.
  • It removes those unused objects to free up the memory and making space for new objects.
  • New objects are collected more frequently than older objects, which helps improve efficiency.
  • You can request garbage collection using System.gc(), but the JVM ultimately decides when it should run.

Object Structure in Java

In Java, an object consists of three main parts:

  • Object header: It contains metadata like the object's class and lock information for synchronization.
  • Instance data: It refers to the actual fields or variables that belongs to an object.
  • Padding: It refers to the extra memory to align the object size to the word size for better performance.

The object header includes:

  • Class Pointer: This is a reference to the object's class.
  • Lock Information: This is used for synchronization in multithreaded programs.
  • GC-related Information: It is used by the garbage collector for managing the object lifecycle.

Finalize method

  • Method of object class
  • Used to perform cleanup operations before an object is garbage collected
  • Affects objects, specifically by overriding the method in a class
  • Called by the garbage collector when an object is about to be deleted, but it's not guaranteed to run

Stack vs Heap Memory Comparison

Parameter STACK HEAP
Basic Memory is allocated in a contiguous block. Memory is allocated in any random order.
Allocation and De-allocation Automatic by compiler instructions. Manual by the programmer (in C or C++ and garbage collector in Java or Python)
Cost Less More
Implementation Easy Hard
Main Issue Shortage of memory Memory fragmentation
Locality of reference Excellent Adequate
Safety Thread safe, data stored can only be accessed by the owner Not Thread safe, data stored visible to all threads
Flexibility Fixed-size Resizing is possible
Data type structure Linear Hierarchical
Preferred Static memory allocation is preferred in an array. Heap memory allocation is preferred in the linked list.
Size Smaller than heap memory. Larger than stack memory.