Explain Codes LogoExplain Codes Logo

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

java
reflection
system-monitoring
cpu-usage
Nikita BarsukovbyNikita Barsukov·Feb 12, 2025
TLDR

Quickly gauge your system's resources in Java by exploiting the OperatingSystemMXBean for CPU and memory statistics, and FileStore for disk space details—all conveniently available in the java.lang.management and java.nio.file packages:

import java.lang.management.ManagementFactory; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Paths; public class SysMonitor { public static void main(String[] args) throws Exception { var osBean = ManagementFactory.getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class); // Pull the car over; we need to check the engine (CPU Usage) System.out.printf("CPU Usage: %.2f%%\n", osBean.getSystemCpuLoad() * 100); // Don't have too much going on in your attic... (Used Memory) var memUsed = (osBean.getTotalPhysicalMemorySize() - osBean.getFreePhysicalMemorySize()) / (1024 * 1024); System.out.printf("Used Memory: %dMB\n", memUsed); // Keep your storage room clean! (Disk Usage) FileStore store = Files.getFileStore(Paths.get("/")); System.out.printf("Disk Used: %dGB\n", (store.getTotalSpace() - store.getUsableSpace()) / (1024 * 1024 * 1024)); } }

Can't get simpler than that—compile, run and voila: you have your system stats on demand!

Method reflection for advanced metrics

If you're that type who isn't easily satisfied with the basics, you can utilize reflection to access under-the-hood metrics. By iterating through the getDeclaredMethods(), we can tap into additional management properties label which may not be made public. Here's the magicians' secret.

import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class AdvancedSysMonitor { public static void main(String[] args) { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); for (Method method : osBean.getClass().getDeclaredMethods()) { if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) { try { System.out.println(method.getName() + " = " + method.invoke(osBean)); } catch (Exception e) { // Because some days, technology just disobeys. e.printStackTrace(); } } } } }

Embracing SIGAR for professional monitoring

If you aim for precision and platform-independent system monitoring, the golden ticket is SIGAR API. Thanks to its open-source nature and Apache 2.0 licensing, SIGAR allows fetching various real-time system metrics. Let's dive into commercial-grade resource monitoring.

// Pseudocode for SIGAR usage - actual use would require the SIGAR library and initialization import org.hyperic.sigar.Sigar; Sigar sigar = new Sigar(); System.out.println("CPU Usage: " + sigar.getCpuPerc()); System.out.println("Memory Usage: " + sigar.getMem().getUsedPercent()); System.out.println("Disk Usage: " + sigar.getFileSystemUsage("/path/to/dir").getUsePercent());

Note the need to initialize the library and add necessary error handling, but remember, with great power comes... well, you know.

Aiming for consistent and accurate monitoring

Periodic and repeated verification of metrics is crucial. CPU usage is a slippery fish—capture it over a period with system timing using System.nanoTime(). A time-lapse is often a better estimator of the CPU load than an instantaneous snapshot.

Bridging gaps across platforms

Is your application a globetrotter across diverse environments? Then being aware of platform-specific quirks and writing adaptive code is a mandate. Remember to glide smoothly without tripping over—so gather those less detailed stats when richer ones elude you.

Tapping into native system metrics

Java is generous with its monitoring toolset, but sometimes, native system metrics can dish out the extra detailing for resource optimization. That's where libraries like oshi and Prometheus step in to illuminate that extra mile for you.