Skip to content

Quick Start

zhenya edited this page Aug 12, 2025 · 19 revisions

This page provides a quick introduction to using Java System Monitor in your applications.

Usage examples

System information

Get basic system information using static methods:

out.printf("Available processors: %d%n",              SystemMonitor.getAvailableProcessors());
out.printf("Available memory: %d bytes%n",            SystemMonitor.getAvailableMemory());
out.printf("OS name: %s%n",                           SystemMonitor.getOperatingSystemName());
out.printf("OS version: %s%n",                        SystemMonitor.getOperatingSystemVersion());
out.printf("JVM name: %s%n",                          SystemMonitor.getJVMName());
out.printf("JVM vendor: %s%n",                        SystemMonitor.getJVMVendor());
out.printf("Supported Java version: %s%n",            SystemMonitor.getSupportedJavaVersion());
out.printf("Supported system-wide CPU metrics: %s%n", SystemMonitor.isSystemCpuUsageSupported());

Sample output:

Available processors: 8
Available memory: 15246819328 bytes
OS name: Windows 10
OS version: 10.0
JVM name: Java HotSpot(TM) 64-Bit Server VM
JVM vendor: Oracle Corporation
Supported Java version: 1.8
Supported system-wide CPU metrics: true

Lazy monitoring

LazySystemMonitor updates usage metrics on demand for applications that need periodic monitoring with minimal overhead:

// Create a lazy monitor with 1-second update threshold
try (final SystemMonitor monitor = LazySystemMonitor.withUpdateThreshold(Duration.ofSeconds(1))) {
            
    // Get current metrics (will update on first call or if the threshold time elapsed)
    final CpuUsage cpu = monitor.getCpuUsage();
    final MemoryUsage memory = monitor.getMemoryUsage();
    
    ...

    out.printf("Process CPU: %.2f%%%n",   cpu.getProcessCpuLoad());
    out.printf("System CPU: %.2f%%%n",    cpu.getSystemCpuLoad());
    out.printf("Used memory: %d bytes%n", memory.getUsedMemory());
}

Background monitoring

BackgroundSystemMonitor uses a daemon background thread with an optional callbacks to continuously monitor usage metrics:

For applications that need continuous monitoring in the background:

// Create a background monitor that updates every second
try (final BackgroundSystemMonitor monitor = BackgroundSystemMonitor
                        .updateEvery(Duration.ofSeconds(1))
                        .onUpdate((cpu, memory) ->
                            out.printf("process-cpu: %s, system-cpu; %s used-memory: %s%n", formatPercent(cpu.getProcessCpuLoad()), formatPercent(cpu.getSystemCpuLoad()), formatDecimalBytes(memory.getUsedMemory())))
                        .onClose((cpu, memory) ->
                            out.printf("avg. process-cpu: %s, avg. system-cpu %s, max. used-memory: %s%n", formatPercent(cpu.getAverageProcessCpuLoad()), formatPercent(cpu.getAverageSystemCpuLoad()), formatDecimalBytes(memory.getMaxUsedMemory())))
                        .start()) {  // Don't forget to start the monitor

    ... // Do work

} // Automatically close/stop the monitor

Formatting utilities

Use the Formatter class for human-readable output:

import static software.leonov.system.monitor.util.Formatter.*;
...

final CpuUsage cpu = monitor.getCpuUsage();
final MemoryUsage memory = monitor.getMemoryUsage();

...

// Format percentages
System.out.println("CPU: " + formatPercent(cpu.getSystemCpuLoad()));

// Format memory in binary units (1024-based)
System.out.println("Memory: " + formatBinaryBytes(memory.getUsedMemory()));

// Format memory in decimal units (1000-based)  
System.out.println("Memory: " + formatDecimalBytes(memory.getUsedMemory()));

Sample output:

CPU: 23.5%
Memory: 512MiB
Memory: 537MB

Error handling

Instead of throwing exceptions this library returns negative values if the requested information is unavailable, uninitialized, or is unsupported on the underlying. SystemMonitor.isSystemCpuUsageSupported() returns true if the system-wide CPU usage metrics are supported on the underlying JVM.

final CpuUsage cpu = monitor.getCpuUsage();

if (SystemMonitor.isSystemCpuUsageSupported())
    System.out.println("System CPU load is not available on this platform");
else if (cpu.getSystemCpuLoad() < 0)
    System.out.println("System CPU load not ready");
else
    System.out.println("System CPU is: " + cpu.getProcessCpuLoad() + "%");

Best practices

The monitor update period should be made as infrequent as possible to minimize the inherit cost (i.e. system calls, CPU cycles, etc...) of collecting usage metrics.

// Avoid - sub-second intervals unless absolutely necessary
BackgroundSystemMonitor.updateEvery(Duration.ofMillis(100))

// Good - 1-5 second intervals for most applications
BackgroundSystemMonitor.updateEvery(Duration.ofSeconds(1))

// Better - 10-30 seconds for less critical monitoring for long running tasks
BackgroundSystemMonitor.updateEvery(Duration.ofSeconds(10))

Consider implementing periodic reporting that coincides with natural application boundaries, such as task completion or logging intervals:

try (final SystemMonitor monitor = LazySystemMonitor.withDefaultUpdateThreshold()) {
    
    while (hasNextTask()) { // Let's assume we have a lot of CPU and memory intensive tasks to run
        final Task task = getNextTask();
        
        // Execute expensive task
        final Result result = task.execute();
        
        logger.info("Task %s completed: %s", task.getName(), result);
        
        // Report metrics after task completion
        final CpuUsage cpu = monitor.getCpuUsage();
        final MemoryUsage memory = monitor.getMemoryUsage();
        
        logger.info("CPU Usage: %s, memory usage: %s", cpu, memory);
    }
}