Explain Codes LogoExplain Codes Logo

Get OS-level system information

java
system-information
memory-statistics
cpu-usage
Nikita BarsukovbyNikita Barsukov·Oct 27, 2024
TLDR

To quickly fetch basic OS-level system information in Java use:

String osInfo = String.format("OS Name: %s, Version: %s, Architecture: %s", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch")); System.out.println(osInfo);

Locating detailed stats such as memory:

OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); Method m = osBean.getClass().getMethod("getFreePhysicalMemorySize"); System.out.println("Free Physical Memory: " + m.invoke(osBean));

Remember to handle those pesky security exceptions when accessing system properties.

Runtime class: The Memory Architect

For getting meticuluous details about the Memory Statistics and CPU one should utilize the Runtime class.

// "Runtime" class - feels like a superhero from a comic-book. int cpuCores = Runtime.getRuntime().availableProcessors(); // CPU Cores, not apple cores! System.out.println("Available Processors: " + cpuCores); Runtime runtime = Runtime.getRuntime(); // "Runtime", I choose you! System.out.println("Free memory: " + runtime.freeMemory()); // Free memory, not free beer! System.out.println("Max memory: " + runtime.maxMemory()); // Now, show me, what's your limit? System.out.println("Total memory: " + runtime.totalMemory()); // Total memory, not Total Recall!

java.io.File: The Disk Depth Diver

For going deep into disk usage metrics, java.io.File is your companion:

File[] roots = File.listRoots(); for (File root : roots) { System.out.println("Root: " + root.getAbsolutePath()); System.out.println("Total Space: " + root.getTotalSpace()); System.out.println("Free Space: " + root.getFreeSpace()); System.out.println("Usable Space: " + root.getUsableSpace()); }

MXBeans: The System Little Birdies

For those hearty folks who like to dive deeper, ManagementFactory and MXBeans are the sherpas on this data-excursion:

MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); System.out.println("Heap Memory Usage: " + memoryMXBean.getHeapMemoryUsage()); System.out.println("Non-Heap Memory Usage: " + memoryMXBean.getNonHeapMemoryUsage());

For the sneaky Process Metrics, as CPU load, we just do a little Oceans' 11 and cast OperatingSystemMXBean:

if (osBean instanceof com.sun.management.OperatingSystemMXBean) { com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) osBean; System.out.println("Process CPU load: " + sunOsBean.getProcessCpuLoad()); }

Tips: Claim a Free CPU Usage Update every minute (or more frequent) at the GetCpuUsage Store!

Meet the League of Extraordinary Libraries

Sometimes, you need to call in for reinforcements:

  • SIGAR API: It's the Captain America of System Metrics. It's reliable, robust, can handle anything..almost! (deprecated)
  • OSHI project: Now this one is like Iron Man, cutting-edge, feature-rich, and backed 100% by Java:
SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); CentralProcessor processor = hal.getProcessor(); System.out.println("Processor Identifier: " + processor.getProcessorIdentifier());

Avoid The Murder Mystery of JNI and opt for Java-native suitors like OSHI or JNA-based libraries.

Trivia: Cross-Platform Compatibility

  • Ensure methods are platform-independent, unless you endorse digital discrimination (pun intended!).
  • Prepare fallbacks or conditional logic for OS-specific metrics because sometimes, Apple doesn't like Oranges.
  • Check OSHI's compatibility, this creature has its own unique habitat preferences.

Your Canvas: Practical Use Cases

You can now craft your own:

  • System monitoring tools: Who wouldn't like some live, detailed performance metrics?
  • Benchmarking applications: "Are we fast yet?", your hardware would certainly like to know!

Allocate O(0), learn about optimizing retrieval frequencies and granularity suited to your needs.