What are the differences between Heap and Stack Memory in Java?

Learn the differences between heap and stack memory in Java. By Preeti Jain Last updated : March 25, 2024

In Java programming, memory plays an important role in storing and managing data during program execution. When it comes to memory allocation, JVM (Java Virtual Machine) divides the memory into two components: stack memory and heap memory. In this article, we'll cover the difference between stack and heap memory in detail with relevant examples.

Stack Memory in Java

For stack memory, JVM creates a separate runtime stack for every individual thread at the time of thread instantiation (creation). No new keyword is required for stack memory.

Stack memory is used for storing method invocation frames, local variables, and reference variables. Each thread in Java has its stack memory.

Every method call performed by that thread and method will be stored in the corresponding runtime stack (i.e. newly created thread is responsible for calling its method and the method entry will be stored in desired run-time stack at the time of that thread instantiation).

Once you call a method in Java, a new "frame" is added to the stack. This frame contains information about the method, like its parameters and local variables. As the method runs, it uses this space to store temporary data and keep track of where it is in the program. Once the method finishes, its frame is removed from the stack.

Stack frame are made up of three parts:

  1. Local variable array:
    • It contains all arguments (or parameters) and local variables of the methods.
    • Each block in array is of 4 bytes Values of int, float and reference occupy only one block and double and long occupy two block and byte, short and char will be converted into int before storing.
  2. Operand stack:
    • It is a stack to perform intermediate data or results.
    • Frame Data: It contains constants and reference to exception table which provide corresponding catch block information in the case of exception.

Example of stack memory

class ChildThread extends Thread {
  public void run() {
    System.out.println("I am in child thread");
  }

}

class MainThread {
  public static void main(String[] args) {
    ChildThread ct = new ChildThread();
    ct.start();

    public static void m1() {
      System.out.println("I am in main thread");
    }
  }

In the above example, we have two threads:

  1. Main thread
  2. Child thread
Runtime stack for Child Runtime stack for Main
run() m1() method
main() method

Explanation

  • After executing method the corresponding method entry from the stack will be removed.
  • After executing all method calls the stack will become empty and that empty stack will be destroyed by the JVM before terminating the thread.
  • Stack memory is not global (i.e. one stack variable or methods can't be used in another stack).
  • Each entry in the stack is called stack frame or activation records.
  • JVM creates a separate runtime stack for every thread (i.e data stored in the stack is available to the corresponding thread only and another thread can't access that data it means data is private to that thread and that’s why we call it is thread safe).

Heap Memory in Java

Heap memory will be created at the time of JVM startup. The "new" keyword is required for heap memory. Heap memory contains Object and Object contains instance data (i.e. heap contains Object and instance data).

Heap memory in Java is like a large storage space where objects are stored. When you create an object in Java using the new keyword, it's allocated memory in the heap.

The data stored in heap memory is not thread-safe (i.e. Object of one thread will be shared by another thread and the data is not private). Only one heap memory is allowed (not like stack memory) and that memory will be shared by multiple threads.

We can create a Runtime object and once we get Runtime object then we call Runtime-specific methods like, maxMemory(), totalMemory(), freeMemory()

Objects stored in heap memory exist beyond the scope of the method that created them, as long as there are references to them.

Sample

Runtime r = Runtime.getRuntime();

r.maxMemory();
r.totalMemory();
r.freeMemory();

Explanation

  1. maxMemory(): It returns the number of bytes of max memory allocated to the heap.
  2. totalMemory(): It returns the number of bytes of total memory allocated to the heap.
  3. freeMemory(): It returns the number of bytes of free memory present in the heap.

Example of heap memory

class Heap{
    public static void main(String[] args){
        Runtime r = Runtime.getRuntime();

        long max_memory = r.maxMemory();
        long total_memory = r.totalMemory();
        long free_memory = r.freeMemory();

        System.out.println(" Maximum Memory in bytes " + max_memory);
        System.out.println(" Total Memory in bytes " + total_memory);
        System.out.println(" Free Memory in bytes " + free_memory);
    }
}

Output:

D:\Java Articles>java Heap
Maximum Memory in bytes 1888485376
Total Memory in bytes 128974848
Free Memory in bytes 127611672

Differences Between Stack and Heap Memories in Java

The following tables shows the main differences between stack and heap memories in Java:

Sr. No. Stack Memory Heap Memory
1. In Java, each thread has its own stack memory. The heap memory is shared among all threads.
2. The stack memory is used for storing method invocation frames, local variables, and reference variables. The heap memory is used for dynamic memory allocation and storing objects and their instance variables.
3. The stack memory has faster access compared to heap memory. The heap memory has slower access compared to stack memory.
4. The Java variables in stack memory have a limited lifetime. Objects in heap memory can remain accessible even after the method has been executed.
5. The stack memory has the limited size and determined by the JVM. The heap memory has dynamically allocated size.
6. The stack memory does not suffer from fragmentation. The heap memory can suffer from fragmentation over time.
7. The stack memory is managed automatically by JVM. The heap memory requires manual management like garbage collection.
8. The stack memory is local to each thread. The heap memory is shared among all threads.

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.