Memory Management and Garbage Collection

Memory Management and Garbage Collection in Java

Memory Management Basics

Java uses an automatic memory management system that divides memory into several areas, primarily:

  • Heap Memory: Where all objects and class instances are allocated.
  • Stack Memory: Stores local variables and method call information.

The JVM Heap is the main area managed during runtime, and it’s subject to allocation and deallocation of objects dynamically.

Role of Garbage Collection (GC)

  • Java automatically frees memory occupied by objects that are no longer reachable by any part of the program — this process is called Garbage Collection.
  • The JVM runs the Garbage Collector in the background to reclaim unused memory, helping to prevent memory leaks and optimize performance.

Monitoring Memory Using Runtime Class

The java.lang.Runtime class provides useful methods to monitor JVM memory usage:

Example usage:

Runtime runtime = Runtime.getRuntime();
System.out.println("Free Memory: " + runtime.freeMemory());
System.out.println("Total Memory: " + runtime.totalMemory());
System.out.println("Max Memory: " + runtime.maxMemory());Code language: JavaScript (javascript)

Invoking Garbage Collection

While the JVM automatically decides when to perform garbage collection, you can suggest a GC run by calling.

Example Program

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

        System.out.println("Free Memory before creating objects: " + runtime.freeMemory());

        // Create objects to consume memory
        for (int i = 0; i < 10000; i++) {
            new String("Garbage " + i);
        }

        System.out.println("Free Memory after creating objects: " + runtime.freeMemory());

        // Suggest garbage collection
        runtime.gc();

        System.out.println("Free Memory after calling gc(): " + runtime.freeMemory());
    }
}
/*
Free Memory before creating objects: 12345678
Free Memory after creating objects: 11023456
Free Memory after calling gc(): 12104567
*/

Memory management in Java is largely automatic, thanks to its built-in garbage collection (GC) mechanism, which helps developers by automatically reclaiming memory occupied by objects that are no longer in use. This process ensures efficient use of the heap, preventing memory leaks and reducing the chances of OutOfMemoryError.

The java.lang.Runtime class plays a crucial role by providing methods to monitor the JVM’s memory usage and interact with the garbage collector. Through methods like freeMemory(), totalMemory(), and maxMemory(), developers can get valuable insights into memory consumption. Additionally, the gc() method allows programs to suggest when garbage collection should occur, aiding in timely cleanup of unused objects.

Scroll to Top