javacpu-usageoshi

How to get cpu usage using java?


I would like to get cpu usage to update my database using java continuously. At the first loop, this code is readable the correct cpu usage. After then, it returns wrong values less than 0. So, I stucked.

I used jdk 1.8.124.

plz, let me know how to get cpu usage continuously.

lib

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.HardwareAbstractionLayer;

src

public static void main(String[] args) {
  OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
      .getOperatingSystemMXBean();

  while (true) {
    System.out.println(bean.getProcessCpuLoad());
    System.out.println(bean.getSystemCpuLoad());
        try {
            Thread.sleep(3000);
        }
        catch (Exception e){
            System.out.println(e.toString());
            break;
        }
  }

}

Solution

  • It's done by using Oshi lib.

    I can get cpu usage every 20 seconds lib

    import oshi.SystemInfo;
    import oshi.hardware.CentralProcessor;
    import oshi.hardware.HardwareAbstractionLayer;
    

    src

    private SystemInfo si = new SystemInfo();
    private HardwareAbstractionLayer hal = si.getHardware();
    private CentralProcessor cpu = hal.getProcessor();
    long[] prevTicks = new long[TickType.values().length];
    
    public static double getCPU()
    {
        double cpuLoad = cpu.getSystemCpuLoadBetweenTicks( prevTicks ) * 100;
        prevTicks = cpu.getSystemCpuLoadTicks();
        System.out.println("cpuLoad : " + cpuLoad);
        return cpuLoad;
    }
    
    public static void main(String[] args) throws Exception{
        while(true) {
            // Sleep 20 seconds
            tCPU = (int)getCPU();
        }
    }