在Java中,可以使用ManagementFactory
類來讀取JVM內存信息。下面是一個示例代碼:
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
public class JVMMemoryReader {
public static void main(String[] args) {
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
System.out.println("Heap Memory Usage:");
System.out.println(" Init: " + heapMemoryUsage.getInit());
System.out.println(" Used: " + heapMemoryUsage.getUsed());
System.out.println(" Committed: " + heapMemoryUsage.getCommitted());
System.out.println(" Max: " + heapMemoryUsage.getMax());
System.out.println("Non-Heap Memory Usage:");
System.out.println(" Init: " + nonHeapMemoryUsage.getInit());
System.out.println(" Used: " + nonHeapMemoryUsage.getUsed());
System.out.println(" Committed: " + nonHeapMemoryUsage.getCommitted());
System.out.println(" Max: " + nonHeapMemoryUsage.getMax());
}
}
運行上述代碼會輸出JVM的堆內存和非堆內存的使用情況。