Quantcast
Viewing all articles
Browse latest Browse all 3675

Introduction to OSHI

Image may be NSFW.
Clik here to view.

1. Overview

In this tutorial, we’ll learn something interesting that could help us know our system. Whenever we think about checking CPU usage, memory status, or disk space in Java, we might ask ourselves, Do I need to call system commands or use JNI? Nope! That’s where OSHI (Operating System and Hardware Information) comes in.

OSHI is a pure Java library that helps us fetch system-level details without any native dependencies. It acts as a bridge between our Java application and system APIs, pulling useful information about the OS, hardware, and network in a cross-platform manner.

2. Why Use OSHI for System Monitoring?

We might wonder, “Why not just use Runtime.exec() or System.getProperty()?” Well, those approaches are limited. System.getProperty() can only fetch the OS name and version, while Runtime.exec() requires OS-specific commands.

OSHI, on the other hand, works with the most popular operating systems (Windows, macOS, Linux). It provides deep system insights about CPU, RAM, disks, sensors, and networks. It doesn’t require native code since it is fully Java-based, and last but not least, it’s lightweight and easy to use – we just need to add a dependency.

3. Key Features and Advantages

With OSHI, we can:

  • Get OS details: name, version, architecture, and uptime
  • Monitor CPU usage, core details, and processor speed
  • Fetch memory statistics: total RAM, available memory, swap usage
  • Retrieve disk storage information: partitions, read/write speed
  • Track network interfaces, IP addresses, and bandwidth usage
  • Access sensor data like CPU temperature, fan speeds, and voltages (if supported)

Now, let’s move further and see how we can implement these features.

4. Setting up OSHI in a Java Project

Before we dive into the fun stuff, let’s get OSHI into our project.

If we’re using Maven, we need to add the oshi-core dependency to our pom.xml:

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>6.4.2</version>
</dependency>

Once added, OSHI will be ready to roll out!

5. Retrieving Basic System Information

Now that OSHI is set up, let’s start with the basics: fetching OS details and checking system uptime.

5.1. Fetching Operating System Details

Think of our OS as the brain of the machine. Wouldn’t it be nice to know what OS we’re running on, which version, and whether it’s 32-bit or 64-bit?

Let’s see how easily we can do that with OSHI:

@Test
void givenSystem_whenUsingOSHI_thenExtractOSDetails() {
    SystemInfo si = new SystemInfo();
    OperatingSystem os = si.getOperatingSystem();
    assertNotNull(os, "Operating System object should not be null");
    assertNotNull(os.getFamily(), "OS Family should not be null");
    assertNotNull(os.getVersionInfo(), "OS Version info should not be null");
    assertTrue(os.getBitness() == 32 || os.getBitness() == 64, "OS Bitness should be 32 or 64");
}

The code creates a SystemInfo object from the OSHI library to access system-related details. It then retrieves the OperatingSystem instance, which provides information like the OS family, version, and bitness.

5.2. Checking System Uptime

Ever wondered how long our system has been running without a reboot? System uptime tells us just that:

@Test
void givenSystem_whenUsingOSHI_thenExtractSystemUptime() {
    SystemInfo si = new SystemInfo();
    OperatingSystem os = si.getOperatingSystem();
    long uptime = os.getSystemUptime();
    assertTrue(uptime >= 0, "System uptime should be non-negative");
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        fail("Test interrupted");
    }
    long newUptime = os.getSystemUptime();
    assertTrue(newUptime >= uptime, "Uptime should increase over time");
}

Here, we retrieve the system uptime using OSHI by creating a SystemInfo object and accessing the OperatingSystem instance. The test first checks that the system uptime is non-negative, ensuring a valid value. Then, it pauses for two seconds using Thread.sleep(2000), handling interruptions. After the delay, it fetches the system uptime again, which can be used to verify that the uptime increases over time.

If we see something like 3600 seconds, our machine has been up for an hour.

6. CPU Monitoring with OSHI

The CPU (Central Processing Unit) is the heart of any system. Monitoring its usage, load, and core count is essential for performance tuning.

6.1. Getting Processor Details

OSHI makes it easy to fetch our processor’s name, core count, and clock speed using Java:
@Test
void givenSystem_whenUsingOSHI_thenExtractCPUDetails() {
    SystemInfo si = new SystemInfo();
    CentralProcessor processor = si.getHardware().getProcessor();
    assertNotNull(processor, "Processor object should not be null");
    assertTrue(processor.getPhysicalProcessorCount() > 0, "CPU must have at least one physical core");
    assertTrue(processor.getLogicalProcessorCount() >= processor.getPhysicalProcessorCount(),
      "Logical cores should be greater than or equal to physical cores");
}
This test initializes a SystemInfo object from OSHI and retrieves the CentralProcessor instance from the system’s hardware. The CentralProcessor provides details about the CPU, such as the number of cores, processor identifiers, and load metrics, though no assertions or validations are present in this snippet.

The method processor.getPhysicalProcessorCount() returns the number of physical CPU cores in the system. It ensures the system has at least one physical core, and processor.getLogicalProcessorCount() returns the number of logical processors, including hyper-threaded cores.

6.2. Measuring CPU Load Dynamically

If we want to check how busy our CPU is at a given moment, we can easily do so:

@Test
void givenSystem_whenUsingOSHI_thenExtractCPULoad() throws InterruptedException {
    SystemInfo si = new SystemInfo();
    CentralProcessor processor = si.getHardware().getProcessor();
    long[] prevTicks = processor.getSystemCpuLoadTicks();
    TimeUnit.SECONDS.sleep(1);
    double cpuLoad = processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100;
    assertTrue(cpuLoad >= 0 && cpuLoad <= 100, "CPU load should be between 0% and 100%");
}

The code captures the system’s CPU load ticks (prevTicks), waits for one second, and calculates the CPU load percentage between the recorded ticks using getSystemCpuLoadBetweenTicks(prevTicks) * 100. Finally, it asserts that the CPU load falls within the valid range of 0% to 100%, ensuring the correctness of the OSHI-reported CPU utilization.

A lower percentage means our CPU is idle, while a higher percentage indicates a high workload.

7. Memory Monitoring

Our system’s RAM (Random Access Memory) determines how many applications can run simultaneously.

7.1. Retrieving Total and Available RAM

Let’s see how we can retrieve the total and available RAM for our system:

@Test
void givenSystem_whenUsingOSHI_thenExtractMemoryDetails() {
    SystemInfo si = new SystemInfo();
    GlobalMemory memory = si.getHardware().getMemory();
    assertTrue(memory.getTotal() > 0, "Total memory should be positive");
    assertTrue(memory.getAvailable() >= 0, "Available memory should not be negative");
    assertTrue(memory.getAvailable() <= memory.getTotal(), "Available memory should not exceed total memory");
}

The code initializes a SystemInfo object and obtains the GlobalMemory instance, which provides memory-related information. It asserts that the total memory is positive, ensuring the system has valid RAM. It also checks that the available memory is non-negative and doesn’t exceed the total memory, validating OSHI’s memory reporting.

7.2. Storage and Disk Information

@Test
void givenSystem_whenUsingOSHI_thenExtractDiskDetails() {
    SystemInfo si = new SystemInfo();
    List<HWDiskStore> diskStores = si.getHardware().getDiskStores();
    assertFalse(diskStores.isEmpty(), "There should be at least one disk");
    for (HWDiskStore disk : diskStores) {
        assertNotNull(disk.getModel(), "Disk model should not be null");
        assertTrue(disk.getSize() >= 0, "Disk size should be non-negative");
    }
}
The code retrieves disk storage details using OSHI. It fetches the list of HWDiskStore instances, representing system disks. It ensures that at least one disk is present, then iterates through each disk, verifying that the model name isn’t null and the disk size is non-negative. This ensures OSHI correctly detects and reports disk information.

8. Limitations of OSHI

While OSHI is feature-rich, it does have some limitations:

  • Sensor data availability depends on hardware support: Not all machines expose temperature or voltage readings
  • Limited low-level control: OSHI provides read-only system insights; it doesn’t allow system modifications
  • Dependency on system APIs: Some information may vary slightly between operating systems

9. Conclusion

In this article, we saw that OSHI is a powerful yet lightweight Java library for retrieving system and hardware information. It eliminates the hassle of dealing with native system commands, JNI, or platform-specific dependencies, making it a great choice for developers who need cross-platform system monitoring.

As always, the code presented in this article is available over on GitHub.

The post Introduction to OSHI first appeared on Baeldung.Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 3675

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>