Skip to content

Quick Start

zhenya edited this page Aug 11, 2025 · 19 revisions

Quick Start

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 callback to continuously monitor usage metrics:

For applications that need continuous monitoring in the background:

// Create a background monitor that updates every second
try (SystemMonitor monitor = BackgroundSystemMonitor
                                    .updateEvery(Duration.ofSeconds(1))
                                    .onUpdate((cpu, memory) -> {
                                        logger.info(...);
                                    })
                                    .start()) {  // Don't forget to start() the monitor
    
    ...
    
} // Automatically stops 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()));

Example output:

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

Error Handling

Instead of throwing exceptions this library returns negative values if the requested the requested information is unavailable, uninitialized, or is unsupported on the underlying.

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

Update Period Optimization

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

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

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

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

Periodic Reporting

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

try (SystemMonitor monitor = LazySystemMonitor.withDefaultUpdateThreshold()) {
    
    while (hasNextTask()) { // Let's assume we have a lot of CPU and memory intensive task to execute
        final Task task = getNextTask();
        
        // Execute expensive task
        final Result result = task.execute();
        
        logger.info(..., result);
        
        // Report metrics after task completion
        final CpuUsage cpu = monitor.getCpuUsage();
        final MemoryUsage memory = monitor.getMemoryUsage();
        
        logger.info(...);
    }
}
Clone this wiki locally