温馨提示×

java怎么读取jvm内存

小亿
115
2023-11-27 19:42:21
栏目: 编程语言

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

0