Get Total Amount of Memory, Max Memory and Amount of Free Memory in the JVM


This code example shows how to display the total amount of memory the Java Virtual Machine uses, the maximum amount of memory the JVM will attempt to use and
also the total amount of free memory in the JVM.
It is done through calling the methods totalMemory(), maxMemory() and freeMemory() of the Runtime class.
To obtain an instance of the Runtime class we call the static method getRuntime().
The amount of memory from the different methods are returned in bytes, so we round the numbers by creating an instance of the DecimalFormat class and call the method format() for every value.


import java.text.DecimalFormat;

/**
 * Main.java
 *
 * @author www.javadb.com
 */

public class Main {
    
    /**
     * Displays the total amount of memory, the maximal amount of memory
     * and the total amount of free memory in the Java Virtual Machine.
     */

    public void displayAvailableMemory() {
        
        DecimalFormat df = new DecimalFormat("0.00") ;
        
        //Display the total amount of memory in the Java virtual machine.
        long totalMem = Runtime.getRuntime().totalMemory();
        
        System.out.println(df.format(totalMem 1000000F) + " MB");
        
        //Display the maximum amount of memory that the Java virtual machine will attempt to use.
        long maxMem = Runtime.getRuntime().maxMemory();
        System.out.println(df.format(maxMem 1000000F) + " MB");
        
        //Display the amount of free memory in the Java Virtual Machine.
        long freeMem = Runtime.getRuntime().freeMemory();
        System.out.println(df.format(freeMem 1000000F) + " MB");
        
    }
    
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().displayAvailableMemory();
    }
}


The output from the code could look something like this:


2,03 MB
66,65 MB
1,82 MB

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: