MENU

Get Java memory usage

TOC

Java memoryGet usage Runtime.getRuntime().totalMemory, freeMemory

Java Returns "total," "used," and "maximum available" memory information for the virtual machine.
The description of each item is as follows

  • total amount...Runtime.getRuntime().totalMemory()and is the amount of memory allocated to the Java virtual machine.
  • amount used...Runtime.getRuntime().totalMemory() -Runtime.getRuntime().freeMemory()become,
    Memory usage of objects currently allocated in memory.
  • maximum usable...Runtime.getRuntime().maxMemory()and is the maximum amount of memory that the Java virtual machine will attempt to use.
    If usage approaches the total and garbage collection does not free memory, the Java Virtual Machine expands to the "maximum available".

sample program

/**
 * Total memory capacity and usage of the Java Virtual Machine,
 * Returns information about the maximum amount of memory to attempt to use.
 * @return Java Virtual Machine memory information.
 */
public static String getMemoryInfo() {
    DecimalFormat f1 = new DecimalFormat("#,###KB");
    DecimalFormat f2 = new DecimalFormat("##.#");
    long free = Runtime.getRuntime().freeMemory() / 1024;
    long total = Runtime.getRuntime().totalMemory() / 1024;
    long max = Runtime.getRuntime().maxMemory() / 1024;
    long used = total - free;
    double ratio = (used * 100 / (double)total);
    String info =
    "Java memory information : total = " + f1.format(total) + "," +
    "Used = " + f1.format(used) + " (" + f2.format(ratio) + "%)," +
    "Maximum available = " + f1.format(max);" + f1.format(max)
    return info; }
}


Execution result 1

◆Example of Execution

public static void main(String[] args) {
    System.out.println(getMemoryInfo());
}

◆Output result

Java memory information : Total=1,984KB, usage=458KB (23.1%), maximum available=65,088KB

Execution Result 2

◆Example of Execution
Change the Java heap size and run it.
The Java heap size value can be specified in the Java command options.

java -Xms64m -Xmx512m Main

-Xms initial heap size
Specify the amount of initial memory allocation for the Java virtual machine. The default is 2 MB.
-Xmx maximum heap size
Specify the maximum memory allocation for the Java virtual machine. Default is 64 MB.

public static void main(String[] args) {
    System.out.println(getMemoryInfo());
}

◆Output result

Java memory information : Total=65,088KB, usage=524KB (0.8%), maximum available=520,256KB

Total Runtime.getRuntime().totalMemory()" is-Xmsand "maximum available Runtime.getRuntime().maxMemory()" in the-XmxLink to the

TOC