Example of MemoryUsage in Java
March 25, 2013
MemoryUsage class belongs to the package java.lang.management. MemoryUsage provides the snapshot of memory usage. Object of MemoryUsage is returned by the methods of MemoryPoolMXBean. MemoryUsage gives the information like amount of memory that can be used by java virtual machine. MemoryUsage gives the information of current use of memory by virtual machine etc.
MemoryUsageTest.java
package com.concretepage; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.util.List; public class MemoryUsageTest { class UserThread extends Thread { public void run() { //using getMemoryPoolMXBeans System.out.println("result of getMemoryPoolMXBeans "); List<MemoryPoolMXBean> mpmxList = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean pl : mpmxList) { String name=pl.getName(); System.out.println(name); MemoryUsage mu = pl.getPeakUsage(); System.out.println("---using MemoryUsage---"); // memory that can be used by JVM System.out.println(mu.getCommitted()); // memory that is being used by JVM System.out.println(mu.getUsed()); //memory which has been request initially. System.out.println(mu.getInit()); //max memory that can be requested. System.out.println(mu.getMax()); } } } public static void main(String[] a){ Thread th= new MemoryUsageTest().new UserThread(); Runtime.getRuntime().addShutdownHook(th); } }
result of getMemoryPoolMXBeans Code Cache ---using MemoryUsage--- 2555904 382208 2555904 50331648 PS Eden Space ---using MemoryUsage--- 32899072 1974088 32899072 689569792 PS Survivor Space ---using MemoryUsage--- 5439488 0 5439488 5439488 PS Old Gen ---using MemoryUsage--- 87556096 0 87556096 1400897536 PS Perm Gen ---using MemoryUsage--- 21757952 2762360 21757952 85983232