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

后端 未结 11 2662
粉色の甜心
粉色の甜心 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:07

    The following supposedly gets you CPU and RAM. See ManagementFactory for more details.

    import java.lang.management.ManagementFactory;
    import java.lang.management.OperatingSystemMXBean;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    
    private static void printUsage() {
      OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
      for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
        method.setAccessible(true);
        if (method.getName().startsWith("get")
            && Modifier.isPublic(method.getModifiers())) {
                Object value;
            try {
                value = method.invoke(operatingSystemMXBean);
            } catch (Exception e) {
                value = e;
            } // try
            System.out.println(method.getName() + " = " + value);
        } // if
      } // for
    }
    
    0 讨论(0)
  • 2020-11-22 13:16

    The accepted answer in 2008 recommended SIGAR. However, as a comment from 2014 (@Alvaro) says:

    Be careful when using Sigar, there are problems on x64 machines... Sigar 1.6.4 is crashing: EXCEPTION_ACCESS_VIOLATION and it seems the library doesn't get updated since 2010

    My recommendation is to use https://github.com/oshi/oshi

    Or the answer mentioned above.

    0 讨论(0)
  • 2020-11-22 13:16

    The following code is Linux (maybe Unix) only, but it works in a real project.

        private double getAverageValueByLinux() throws InterruptedException {
        try {
    
            long delay = 50;
            List<Double> listValues = new ArrayList<Double>();
            for (int i = 0; i < 100; i++) {
                long cput1 = getCpuT();
                Thread.sleep(delay);
                long cput2 = getCpuT();
                double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
                listValues.add(cpuproc);
            }
            listValues.remove(0);
            listValues.remove(listValues.size() - 1);
            double sum = 0.0;
            for (Double double1 : listValues) {
                sum += double1;
            }
            return sum / listValues.size();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    
    }
    
    private long getCpuT throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
        String line = reader.readLine();
        Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
        Matcher m = pattern.matcher(line);
    
        long cpuUser = 0;
        long cpuSystem = 0;
        if (m.find()) {
            cpuUser = Long.parseLong(m.group(1));
            cpuSystem = Long.parseLong(m.group(3));
        }
        return cpuUser + cpuSystem;
    }
    
    0 讨论(0)
  • 2020-11-22 13:17

    In JDK 1.7, you can get system CPU and memory usage via com.sun.management.OperatingSystemMXBean. This is different than java.lang.management.OperatingSystemMXBean.

    long    getCommittedVirtualMemorySize()
    Returns the amount of virtual memory that is guaranteed to be available to the running process in bytes, or -1 if this operation is not supported.
    
    long    getFreePhysicalMemorySize()
    Returns the amount of free physical memory in bytes.
    
    long    getFreeSwapSpaceSize()
    Returns the amount of free swap space in bytes.
    
    double  getProcessCpuLoad()
    Returns the "recent cpu usage" for the Java Virtual Machine process.
    
    long    getProcessCpuTime()
    Returns the CPU time used by the process on which the Java virtual machine is running in nanoseconds.
    
    double  getSystemCpuLoad()
    Returns the "recent cpu usage" for the whole system.
    
    long    getTotalPhysicalMemorySize()
    Returns the total amount of physical memory in bytes.
    
    long    getTotalSwapSpaceSize()
    Returns the total amount of swap space in bytes.
    
    0 讨论(0)
  • 2020-11-22 13:21

    Make a batch file "Pc.bat" as, typeperf -sc 1 "\mukit\processor(_Total)\%% Processor Time"

    You can use the class MProcess,

    /*
     *Md. Mukit Hasan
     *CSE-JU,35
     **/
    import java.io.*;

    public class MProcessor {

    public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }

    }

    Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.

    --Mukit Hasan

    0 讨论(0)
  • 2020-11-22 13:25

    This works for me perfectly without any external API, just native Java hidden feature :)

    import com.sun.management.OperatingSystemMXBean;
    ...
    OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
                    OperatingSystemMXBean.class);
    // What % CPU load this current JVM is taking, from 0.0-1.0
    System.out.println(osBean.getProcessCpuLoad());
    
    // What % load the overall system is at, from 0.0-1.0
    System.out.println(osBean.getSystemCpuLoad());
    
    0 讨论(0)
提交回复
热议问题