View Javadoc
1   package com.guinetik.hexafun.examples.sysmon;
2   
3   import java.io.File;
4   import java.lang.management.ManagementFactory;
5   import java.lang.management.MemoryMXBean;
6   import java.lang.management.OperatingSystemMXBean;
7   
8   /**
9    * Real implementation of MetricsProvider using JVM/OS metrics.
10   *
11   * <p>Uses Java's management beans to read actual system metrics.
12   * Note: CPU load may return -1 if not available on the platform.</p>
13   */
14  public class RealMetricsProvider implements MetricsProvider {
15  
16      private final OperatingSystemMXBean osBean;
17      private final MemoryMXBean memoryBean;
18  
19      public RealMetricsProvider() {
20          this.osBean = ManagementFactory.getOperatingSystemMXBean();
21          this.memoryBean = ManagementFactory.getMemoryMXBean();
22      }
23  
24      @Override
25      public double getCpuUsage() {
26          if (
27              osBean instanceof com.sun.management.OperatingSystemMXBean sunBean
28          ) {
29              double load = sunBean.getCpuLoad();
30  
31              // First call returns -1, need to wait and retry
32              if (load < 0) {
33                  try {
34                      Thread.sleep(100); // Let it collect data
35                      load = sunBean.getCpuLoad();
36                  } catch (InterruptedException ignored) {}
37              }
38  
39              if (load >= 0) {
40                  return load * 100.0;
41              }
42          }
43          return -1;
44      }
45  
46      @Override
47      public double getMemoryUsage() {
48          if (
49              osBean instanceof com.sun.management.OperatingSystemMXBean sunBean
50          ) {
51              long total = sunBean.getTotalMemorySize();
52              long free = sunBean.getFreeMemorySize();
53              if (total > 0) {
54                  return ((double) (total - free) / total) * 100.0;
55              }
56          }
57  
58          // Fallback: JVM heap usage (not system memory, but better than nothing)
59          var heap = memoryBean.getHeapMemoryUsage();
60          return ((double) heap.getUsed() / heap.getMax()) * 100.0;
61      }
62  
63      @Override
64      public double getDiskUsage() {
65          // Get all roots and pick the main one
66          File[] roots = File.listRoots();
67          if (roots.length == 0) return -1;
68  
69          // Use first root (C:\ on Windows, / on Unix)
70          File root = roots[0];
71          long total = root.getTotalSpace();
72          long free = root.getUsableSpace(); // usableSpace is more accurate than freeSpace
73  
74          if (total > 0) {
75              return ((double) (total - free) / total) * 100.0;
76          }
77          return -1;
78      }
79  }