How do I monitor the computer's CPU, memory, and disk usage in Java?

后端 未结 11 2672
粉色の甜心
粉色の甜心 2020-11-22 13:02

I would like to monitor the following system information in Java:

  • Current CPU usage** (percent)
  • Available memory* (free/total)
  • Available d

11条回答
  •  太阳男子
    2020-11-22 13:32

    Have a look at this very detailled article: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime

    To get the percentage of CPU used, all you need is some simple maths:

    MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
    
    OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
    mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
    
    long nanoBefore = System.nanoTime();
    long cpuBefore = osMBean.getProcessCpuTime();
    
    // Call an expensive task, or sleep if you are monitoring a remote process
    
    long cpuAfter = osMBean.getProcessCpuTime();
    long nanoAfter = System.nanoTime();
    
    long percent;
    if (nanoAfter > nanoBefore)
     percent = ((cpuAfter-cpuBefore)*100L)/
       (nanoAfter-nanoBefore);
    else percent = 0;
    
    System.out.println("Cpu usage: "+percent+"%");
    

    Note: You must import com.sun.management.OperatingSystemMXBean and not java.lang.management.OperatingSystemMXBean.

提交回复
热议问题