Check Memory Used by a Program in Java



This article will discuss "how to check the memory used by a program" in Java, including a brief introduction of the process for calculation and an appropriate example that correctly checks the memory usage by the program.

Understanding Memory Usage in Java Programs

A Java code that takes a long time to execute, makes heavy use of dynamic memory. In such scenarios, we may end up with Out-of-Memory errors (due to a memory shortage of the heap space).

We can calculate the memory space (heap) used by a Java program using the methods provided by the Runtime class.

If the heap space is used more than 90 percent, then we need to call the garbage collector explicitly.

When we call the garbage collector (using System.gc()). The Java compiler will stop the execution of the current thread until the garbage collector completes its task. Therefore, this code can be executed in a separate thread.

Memory used by a Program using the Runtime Class

Every Java program has an instance of the Runtime class, which represents its runtime environment.

Using this instance, we can interact with the runtime environment (JVM) and perform various operations such as shutting down the process (exit()), calling the garbage collector (gc()), and terminating the JVM (halt()). You can get its instance Runtime.getRuntime().

The Java Runtime class provides methods, such as maxMemory(), totalMemory(), and freeMemory(), which help us to calculate the memory usage and the maximum memory available to the program.

Example

In the following example, we use the maxMemory() method to calculate the maximum memory that the program can use. Then, we determine the final memory usage by subtracting the free memory from the maximum memory:

public class GCTest {
   public void runGC() {
      Runtime runtime = Runtime.getRuntime();
      long memoryMax = runtime.maxMemory();
      System.out.println("The maximum memory: " + memoryMax);
      long memoryUsed = runtime.totalMemory() - runtime.freeMemory();
      double memoryUsedPercent = (memoryUsed * 100.0) / memoryMax;
      System.out.println("The memory used by program (in precent): " + memoryUsedPercent);
      if (memoryUsedPercent > 90.0){
         System.gc();
      }
   }
   public static void main(String args[]) {
      GCTest test = new GCTest();
      test.runGC();
   }
}

The above program displays the total memory used by the program:

The maximum memory: 4206886912
The memory used by program (in precent): 0.39292598887906593
Updated on: 2025-05-14T11:18:07+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements