|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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! | |
Search for code examples on this site
