阅读量:2
在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的堆内存和非堆内存的使用情况。