How to view memory usage in Java
By
Darío Rivera
Posted On
in
Java
As we know, Java's Garbage Collector manages everything related to the cleaning of variables, objects, and others that are no longer needed in the execution of a program. However, we can display or trace the available memory in the Java Virtual Machine once our program is running. For this, it is enough to use Runtime.maxMemory()
, Runtime.totalMemory()
, among other methods. Let's see an example with a simple program.
package com.pleets;
public class MemoryUsageDemo {
public static void main(String[] args) {
System.out.println("Current memory values in JVM\n");
// amount of memory in use
System.out.println("Used: " + (Runtime.getRuntime().totalMemory() + - Runtime.getRuntime().freeMemory()) + " bytes \n");
// amount of free memory
System.out.println("Free: " + Runtime.getRuntime().freeMemory() + " bytes \n");
// total amount of memory
System.out.println("Total: " + Runtime.getRuntime().totalMemory() + " bytes \n");
// the maximum amount that the JVM could reach to use
System.out.println("Maximum: " + Runtime.getRuntime().maxMemory() + " bytes \n");
}
}