如何从代码中获取Java中物理和虚拟内存的当前使用情况?

时间:2019-03-24 15:42:10

标签: java memory memory-management

我需要使用Java代码获取计算机上当前正在使用的物理和虚拟内存的百分比。

1 个答案:

答案 0 :(得分:0)

不确定要完成的操作,但请查看MemoryMXBeanMemoryPoolMXBeans

您可以执行以下操作:

OperatingSystemMXBean osMBean = ManagementFactory.getOperatingSystemMXBean();

RuntimeMXBean runtimeMBean = ManagementFactory.getRuntimeMXBean();

System.out.println("Total physical memory:" + osMBean.getTotalPhysicalMemorySize() / 1024 + "kB");
System.out.println("Free physical memory:" + osMBean.getFreePhysicalMemorySize() / 1024 + "kB" );
System.out.println("Comm. virtual memory:" + osMBean.getProcessCpuTime() / 1024 + "kB" );
System.out.println("Total swap space:" + osMBean.getTotalSwapSpaceSize() / 1024 +" kB" );
System.out.println("Free swap space:" + osMBean.getFreeSwapSpaceSize() / 1024 +" kB" );
System.out.println("Operating system:" + osMBean.getName());
System.out.println("Arch:" + osMBean.getArch());
System.out.println("Processors:" + osMBean.getAvailableProcessors());
System.out.println("Process CPU time:" + osMBean.getProcessCpuTime() );