How to view memory usage in Java

Author
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");
   }
}

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.